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?
int(item)
raises an error ifitem
cannot be converted to an int. It's important to wrap this with atry .. except
block since you're reading from a file, which might have some unexpected values.