Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

python - Convert a string key to int in a Dictionary

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

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 JSON format file

{"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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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)}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...