Python - Replacing key string inside dictionary -


i want replace strings inside dictionary numbers. dictionaries dynamically created using from collections import defaultdict , following:

comp1= defaultdict(list, {'carone': [('182', '511'), ('182', '511')],                           'cartwo':[('140', '551'), ('192', '501')],                           'carthree':[('130', '451'), ('292', '601')]}  

what want:

my aim here replace text string number string , convert entire dictionary integer increase execution speed.

comp1= defaultdict(list, {'1': [('182', '511'), ('182', '511')],                           '2':[('140', '551'), ('192', '501')],                           '3':[('130', '451'), ('292', '601')]} 

what tried

i tried 2 approaches:

first:

comp1 = {comp1:[comp1.replace("carone", "1") k in comp1.items()]} #trying car1 first 

second:

comp1.replace("carone", "1") #replacing car1 '1' in entire document 

but shows following error:

attributeerror: 'collections.defaultdict' object has no attribute 'replace' 

edit:

the strings in file random text , has no number in it. entirely text.

you can use simple dictionary comprehension , last element of keys :

>>> collections import defaultdict  >>>  >>> comp1= defaultdict(list, {'car1': [('182', '511'), ('182', '511')], ...                           'car2':[('140', '551'), ('192', '501')], ...                           'car3':[('130', '451'), ('292', '601')]}  ...  ...  ... ) >>>  >>> {i[-1]:j i,j in comp1.iteritems()} {'1': [('182', '511'), ('182', '511')], '3': [('130', '451'), ('292', '601')], '2': [('140', '551'), ('192', '501')]} >>>  

and more general way independent of string behind number , length of number, can use regex extract last numbers :

>>> import re >>>  >>> {re.search(r'\d+$',i).group():j i,j in comp1.iteritems()} {'1': [('182', '511'), ('182', '511')], '3': [('130', '451'), ('292', '601')], '2': [('140', '551'), ('192', '501')]} >>>  

another example :

>>> comp1= defaultdict(list, {'car01': [('182', '511'), ('182', '511')], ...                           'car25':[('140', '551'), ('192', '501')], ...                           'car123':[('130', '451'), ('292', '601')]}  ... ) >>>  >>> {re.search(r'\d+$',i).group():j i,j in comp1.iteritems()} {'01': [('182', '511'), ('182', '511')], '123': [('130', '451'), ('292', '601')], '25': [('140', '551'), ('192', '501')]} >>>  

after edit must since dictionary items not ordered, can not such thing, instead suggest use ordereddict using dict.setdefault method simulate behavior of defaultdict within oedereddict. iterate on items using enumerate , replace keys index.


Comments