gpt4 book ai didi

python - 将字符串键转换为字典中的 int

转载 作者:IT老高 更新时间:2023-10-28 12:49:47 27 4
gpt4 key购买 nike

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

例如,我想要字典:

{ '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()

有没有办法在加载时直接执行?

最佳答案

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

关于python - 将字符串键转换为字典中的 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21193682/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com