Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing values in a Python list/dictionary?

Tags:

Ok, I am trying to filter a list/dictionary passed to me and "clean" it up a bit, as there are certain values in it that I need to get rid of.

So, if it's looking like this:

"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"...}] 

How would I quickly and easily run through it all and replace all values of "AAA" with something like "XXX"?

Focus is on speed and resources, as these may be long lists and I don't want this process to consume too much time.

like image 315
Crazy Serb Avatar asked Jul 02 '09 20:07

Crazy Serb


2 Answers

DATA = {"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"}]}  for name, datalist in DATA.iteritems():  # Or items() in Python 3.x     for datadict in datalist:         for key, value in datadict.items():             if value == "AAA":                 datadict[key] = "XXX"  print (DATA) # Prints {'records': [{'key3': 'CCC', 'key2': 'BBB', 'key1': 'XXX', 'key4': 'XXX'}]} 
like image 170
RichieHindle Avatar answered Oct 08 '22 04:10

RichieHindle


dic = root['records'][0] for i, j in dic.items():       # use iteritems in py2k     if j == 'AAA':         dic[i] = 'xxx' 
like image 37
SilentGhost Avatar answered Oct 08 '22 02:10

SilentGhost