Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 682
Matteo Avatar asked Jan 17 '14 18:01

Matteo


People also ask

How do you convert string to int in Python?

To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. Use the syntax print(int("STR")) to return the str as an int , or integer.

Can a Key in dictionary be integer?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.

How do you convert a key to a dictionary?

Method #1 : Using map() + split() + loop In this, we perform the conversion of key-value pair to dictionary using map and splitting key-value pairs is done using split().

Are Python dictionary keys strings?

The dictionary webstersDict used strings as keys in the dictionary, but dictionary keys can be any immutable data type (numbers, strings, tuples etc). Dictionary values can be just about anything (int, lists, functions, strings, etc).


2 Answers

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)} 
like image 198
ndpu Avatar answered Sep 23 '22 01:09

ndpu


Similar to Decency's answer, but taking advantage of the object_hook argument:

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 

The main advantage of this method is that, if you ever end up with any nested dicts, the loader will handle each nested dict on its own as it loads the data without you having to write code to walk through your result dict. You could also add in checks for cases where values in lists are not numeric strings or the lists themselves contain dicts as well, if your JSON structure gets more complicated, and if your data will only have lists as the values for your top-level dict you can remove the if isinstance(v, list) else v part.

like image 26
JAB Avatar answered Sep 20 '22 01:09

JAB