简体   繁体   English

Python-将字符串键转换为整数

[英]Python - converting string key to integer

I have dictionary in following order. 我有以下顺序的字典。 This dictionary is dynamically generated using from collections import defaultdict 该字典是使用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 : 您的值是列表,项目是元组,您需要将元组项目转换为int ,您可以使用map函数:

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 : 如果您使用的是python 3,则可以在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. 同样,由于map如果要使结果为元组返回一个列表,则也可以使用此配方。

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. 请注意,这将defaultdict实例替换为新的Plain dict对象。

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. 现在,在列表中值的每个元组也被处理,但在元组的每个字符串转换为整数,而不是试图整个的元组对象转换为整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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