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?