简体   繁体   中英

Python - converting string key to integer

I have dictionary in following order. This dictionary is dynamically generated using from collections import defaultdict

Ref = defaultdict(<type 'list'>, {'344': [('0', '0', '136'), 
('548', '136', '137'), 
('548', '136', '6')],        
'345': [('0', '0', '136'), ('548', '136', '137'), 
('548', '136', '6'), 
('742', '136', '6')]}

What I tried:

From here

Ref = {int(k):[int(i) for i in v] for k,v in Ref.items()}

but i get an error:

TypeError: int() argument must be a string or a number, not 'tuple'

What I want:

I want to convert all keys and values which are in string to integers like

Ref = defaultdict(<type 'list'>, {344: [(0, 0, 136), 
    (548, 136, 137), 
    (548, 136, 6)],        
    345: [(0, 0, 136), (548, 136, 137), 
    (548, 136, 6), 
    (742, 136, 6)]}

Your values are list and the items are tuple you need to convert the tuples items to int ,you can use map function for that :

Ref = {int(k):[map(int,i) for i in v] for k,v in Ref.items()}

And if you are in python 3 you can use a generator expression within tuple :

Ref = {int(k):[tuple(int(t) for t in i) for i in v] for k,v in Ref.items()}

Also since map returns a list if you want the result be a tuple you can use this recipe too.

You are trying to convert the key and the tuples in the value . Your question title suggests you want to convert just the key:

Ref = {int(key): value for key, value in Ref.items()}

This leaves the value untouched. Note that this replaces the defaultdict instance with a new plain dict object.

Your output suggests you also want to convert the values in the tuples to integers. Loop over the tuples too:

Ref = {int(key): [tuple(int(i) for i in t) for t in value]
       for key, value in Ref.items()}

Now each tuple in the list value is also processed, but each string in the tuple is converted to an integer, rather than trying to convert the whole tuple object to an integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM