简体   繁体   English

使用混合键类型将 python 字典中的键从字符串转换为 int 类型

[英]Convert keys from string to int type in python dictionary with mixed key types

Consider a python dictionary that has mixed key types:考虑一个具有混合键类型的 python 字典:

chrDict = {'1':234,'12':45,'23':121,'2':117,'chX':12,'chY':32}

I want to convert those keys in string type into int type which are numeric and leave the rest.我想将那些字符串类型的键转换为整数类型,并留下 rest。 The result I expect is:我期望的结果是:

chrDict = {1:234,12:45,23:121,2:117,'chX':12,'chY':32}

I tried the following:我尝试了以下方法:

chrDict.update((int(i),j) for i,j in chrDict.items())

This gives me the error:这给了我错误:

TypeError: cannot convert dictionary update sequence element #0 to a 
sequence

Then I tried:然后我尝试了:

for i,j in chrDict.items():
    try:
        chrDict.update(int(x),y)
    except:
        pass

But the output I get is not correct, it doesn't change:但是我得到的 output 不正确,它不会改变:

{'1': 234, '12': 45, '23': 121, '2':117, 'chX': 12, 'chY': 32}

Actually I want this to do so that it becomes easier to sort later.实际上我希望这样做,以便以后更容易排序。 Currently if i try:目前,如果我尝试:

sorted(chrDict.items())

It gives me following output:它给了我以下 output:

[('1', 234), ('12', 45), ('2', 117), ('23', 121), ('chX', 12), ('chY', 32)]

The key value 2 should come after key value 1 which is not happening.键值2应该出现在键值1之后,这没有发生。

So please give me some suggestions to tackle this problem.所以请给我一些建议来解决这个问题。 Is there any better approach to this problem?有没有更好的方法来解决这个问题?

Use dictionary comprehension with isdigit() to check for strings that are actually numbers:使用带有isdigit()的字典理解来检查实际上是数字的字符串:

{int(k) if k.isdigit() else k: v for k, v in chrDict.items()}

Example :示例

chrDict = {'1':234,'12':45,'23':121,'2':117,'chX':12,'chY':32}

print({int(k) if k.isdigit() else k: v for k, v in chrDict.items()})
# {1: 234, 12: 45, 23: 121, 2: 117, 'chX': 12, 'chY': 32}

It looks like Austin's post answers your specific query.看起来奥斯汀的帖子回答了您的特定查询。 Note that this is creating a new dictionary (not editing your current dictionary in place).请注意,这是创建一个新字典(不是在原地编辑当前字典)。

Further, Python cannot compare type int to type str to sort a list containing both data types (this will raise a TypeError in Python 3) - so you may wish to consider a different approach, if your ultimate goal is to have a sorted list of mixed data types (or create your own custom comparison).此外,Python 无法将int类型与str类型进行比较以对包含这两种数据类型的列表进行排序(这将在 Python 3 中引发 TypeError) - 因此,如果您的最终目标是获得排序列表混合数据类型(或创建您自己的自定义比较)。

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

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