0
votes

Consider a python dictionary that has mixed key types:

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. 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:

{'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:

[('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.

So please give me some suggestions to tackle this problem. Is there any better approach to this problem?

2

2 Answers

1
votes

Use dictionary comprehension with isdigit() to check for strings that are actually numbers:

{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}
0
votes

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).