我的问题与this one非常相似,除了我有一个列表字典,我有兴趣将每个列表格式string
中的键值和所有元素都更改为{{1} }。
所以例如我想要字典:
int
成为:
{ '1':['1', '2', '3', '4'] , '2':['1', '4'] , '3':['43','176'] }
这可能吗?
因为我从{ 1:[1, 2, 3, 4] , 2:[1, 4] , 3:[43,176] }
格式文件
{“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
有没有办法在加载时直接进行?
答案 0 :(得分:42)
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)}
答案 1 :(得分:4)
与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
这种方法的主要优点是,如果你最终得到任何嵌套的dicts,加载器将自己处理每个嵌套的dict,因为它加载数据而不必编写代码来遍历结果dict。您还可以添加检查,列表中的值不是数字字符串,或者列表本身也包含dicts,如果您的JSON结构变得更复杂,并且您的数据只有列表作为顶级字典的值您可以删除if isinstance(v, list) else v
部分。
答案 2 :(得分:3)
此解决方案适用于您使用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
这产生与上面相同的输出。