Python 在字典中将字符串键转换为 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21193682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:15:15  来源:igfitidea点击:

Convert a string key to int in a Dictionary

pythonjsondictionary

提问by Matteo

My question is very similar to this one, except I have a dictionary of lists and I'm interested in changing both the key value and all elements in every list form stringto int.

我的问题与这个问题非常相似,除了我有一个列表字典并且我有兴趣将每个列表表单中的键值和所有元素都更改stringint.

So for instance I'd like the dictionary:

例如,我想要字典:

{ '1':['1', '2', '3', '4'] , '2':['1', '4'] , '3':['43','176'] }

to become:

成为:

{ 1:[1, 2, 3, 4] , 2:[1, 4] , 3:[43,176] }

Is this possible?

这可能吗?

More in general since I created this dictionary from a JSONformat file

更一般地说,因为我从JSON格式文件创建了这本词典

{"0": ["1", "2", "3", "4"], "1": ["0", "2", "3", "4", "27", "94", "95", "97", "128", "217", "218", "317"], "2": ["0", "1", "3", "4", "94", "95"], "3": ["0", "1", "2", "4", "377"], "4": ["0", "1", "2", "3", "27", "28"], "5": ["6", "7", "8"], "6": ["5", "7", "8"], "7": ["5", "6", "8", "14", "23", "40", "74", "75", "76", "362", "371", "372"], "8": ["5", "6", "7", "66"], "9": ["10", "11", "12"], "10": ["9", "11", "12", "56", "130", "131"]}

{“0”:[“1”,“2”,“3”,“4”],“1”:[“0”,“2”,“3”,“4”,“27”,“94” ", "95", "97", "128", "217", "218", "317"], "2": ["0", "1", "3", "4", "94" ", "95"], "3": ["0", "1", "2", "4", "377"], "4": ["0", "1", "2", "3", "27", "28"], "5": ["6", "7", "8"], "6": ["5", "7", "8"], " 7": ["5", "6", "8", "14", "23", "40", "74","75", "76", "362", "371", "372"], "8": ["5", "6", "7", "66"], "9": ["10 ", "11", "12"], "10": ["9", "11", "12", "56", "130", "131"]}

with the following instructions:

使用以下说明:

json_data = open("coauthorshipGraph.txt")
coautorshipDictionary = json.load( json_data )
json_data.close()

is there a way to do it directly at loading time?

有没有办法在加载时直接做到这一点?

采纳答案by ndpu

d = {'1':'145' , '2':'254' , '3':'43'}
d = {int(k):int(v) for k,v in d.items()}
>>> d
{1: 145, 2: 254, 3: 43}

for lists in values

对于值中的列表

>>> d = { '1':['1', '2', '3', '4'] , '2':['1', '4'] , '3':['43','176'] }
>>> d = {int(k):[int(i) for i in v] for k,v in d.items()}

in your case:

在你的情况下:

coautorshipDictionary = {int(k):int(v) for k,v in json.load(json_data)}

or

或者

coautorshipDictionary = {
    int(k):[int(i) for i in v] for k,v in json.load(json_data)}

回答by Chris Arena

This solution will work for the case where you have an iterable as your value, as in the json you provided.

此解决方案适用于您将迭代作为您的值的情况,如您提供的 json。

my_dict = {"0": ["1", "2", "3", "4"], "1": ["0", "2", "3", "4", "27", "94", "95", "97", "128", "217", "218", "317"], "2": ["0", "1", "3", "4", "94", "95"], "3": ["0", "1", "2", "4", "377"], "4": ["0", "1", "2", "3", "27", "28"], "5": ["6", "7", "8"], "6": ["5", "7", "8"], "7": ["5", "6", "8", "14", "23", "40", "74", "75", "76", "362", "371", "372"], "8": ["5", "6", "7", "66"], "9": ["10", "11", "12"], "10": ["9", "11", "12", "56", "130", "131"]}

output_dict = {}
for key, value in my_dict.iteritems():
    output_dict[int(key)] = [int(item) for item in value]

output_dict

Output:

输出:

{0: [1, 2, 3, 4],
 1: [0, 2, 3, 4, 27, 94, 95, 97, 128, 217, 218, 317],
 2: [0, 1, 3, 4, 94, 95],
 3: [0, 1, 2, 4, 377],
 4: [0, 1, 2, 3, 27, 28],
 5: [6, 7, 8],
 6: [5, 7, 8],
 7: [5, 6, 8, 14, 23, 40, 74, 75, 76, 362, 371, 372],
 8: [5, 6, 7, 66],
 9: [10, 11, 12],
 10: [9, 11, 12, 56, 130, 131]}

For the second part of the question, you can use a dict comprehension in line as you read the file. It's obfuscated as hell though.

对于问题的第二部分,您可以在阅读文件时在线使用字典理解。虽然它被混淆了。

with open('coauthorshipGraph.txt', 'r') as f:
    json_data = { int(key) : [int(item) for item in value] for key, value in json.load(f).iteritems()}

json_data

This yields the same output as above.

这产生与上面相同的输出。

回答by JAB

Similar to Decency's answer, but taking advantage of the object_hookargument:

类似于 Decency 的回答,但利用了这个object_hook论点:

coautorshipDictionary = json.load(json_data, object_hook=lambda d: {int(k): [int(i) for i in v] if isinstance(v, list) else v for k, v in d.items()}) # iteritems() for Python 2

The main advantage of this method is that, if you ever end up with any nested dicts, the loader will handle each nested dict on its own as it loads the data without you having to write code to walk through your result dict. You could also add in checks for cases where values in lists are not numeric strings or the lists themselves contain dicts as well, if your JSON structure gets more complicated, and if your data will only have lists as the values for your top-level dict you can remove the if isinstance(v, list) else vpart.

这种方法的主要优点是,如果您最终得到任何嵌套的 dict,加载器将在加载数据时自行处理每个嵌套的 dict,而无需编写代码来遍历结果 dict。您还可以添加检查列表中的值不是数字字符串或列表本身也包含字典的情况,如果您的 JSON 结构变得更加复杂,并且您的数据是否只有列表作为您的顶级字典的值您可以删除该if isinstance(v, list) else v部分。