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

2024-06-14 19:42:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题与this one非常相似,只是我有一个列表字典,我有兴趣将每个列表表单中的键值和所有元素string更改为int

例如,我想要字典:

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

成为:

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

这可能吗?

从我从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"]}

按照以下说明:

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

有没有办法在装货时直接做?


Tags: json元素表单列表datastring字典open
3条回答

类似于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

这种方法的主要优点是,如果最后出现任何嵌套的dict,加载程序将在加载数据时独立处理每个嵌套的dict,而不必编写代码来遍历结果dict。如果JSON结构变得更复杂,并且数据将只包含作为顶级dict的值列出,您可以删除if isinstance(v, list) else v部分。

这个解决方案将适用于iterable作为值的情况,如您提供的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

输出:

{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]}

对于问题的第二部分,您可以在阅读文件时使用一行dict理解。但它被搞得一团糟。

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

这将产生与上述相同的输出。

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}

对于值中的列表

>>> 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()}

就你而言:

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

或者

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

相关问题 更多 >