在字典中将字符串键转换为int [英] Convert a string key to int in a Dictionary

查看:159
本文介绍了在字典中将字符串键转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题非常类似于这个,除了我有一个列表的字典,我有兴趣在每个列表形式中更改键值和所有元素 string int

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 string to int.

所以例如我想要的字典:

So for instance I'd like the dictionary:

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

成为: / p>

to become:

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

这是可能吗?

因为我从一个 JSON 格式文件创建此字典

More in general since I created this dictionary from a JSON format file


{0 :[1,2,3,4],1:[0,2,3,4,27,94,$ b $ $ b94 ,3:[0,1,2,4,377],4:[​​0,1,2 5:[6,7,8],6:[5,7,8 ],7:
[5,6,8,14,23,40,74,75,76 ,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"]}

具有以下说明:

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



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

推荐答案

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

这篇关于在字典中将字符串键转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆