Reputation: 703
I need to create a new dictionary from the following:
{'FOO': "('BAR','BAA'),('CAR','CAA')", 'FOOO': "('BAAR','BAAA'),('CAAR','CAAA')"}
I want to retrieve items within the strings of tuples in the dictionary values, and create a new dictionary using the original keys and the retrieved items as corresponding values. The retrieved items must be by placement (first item of every tuple). The completed dictionary should look like the following:
{'FOO': ('BAR','CAR'), 'FOOO': ('BAAR','CAAR')
This should be relatively easy, but I've been pulling my hair out trying to make this work.
Upvotes: 2
Views: 166
Reputation: 365817
First, ast.literal_eval
will turn each "('BAR','BAA'),('CAR','CAA')"
into (('BAR', 'BAA'), ('CAR', 'CAA'))
.
Then you can just do [0]
to get the first one. Is that all you were missing?
It's worth noting that, as a general rule, if you're using literal_eval
, you're usually doing something wrong. For example, maybe instead of storing a string literal version of a tuple
, you can store a JSON array, or a pickle
d or marshal
led tuple
.
Upvotes: 2
Reputation:
It might be not the best way to do it, but you can solve it with regular expressions.
import re
di={'FOO': "('BAR','BAA'),('CAR','CAA')",
'FOOO': "('BAAR','BAAA'),('CAAR','CAAA')"}
ndi = {}
for k in di:
ndi[k] = re.findall('\(\'(\w+)\'\,', di[k])
Upvotes: 1
Reputation: 179462
You can use ast.literal_eval
to parse those strings. Then it's just a matter of pulling out the right elements.
d = {'FOO': "('BAR','BAA'),('CAR','CAA')", 'FOOO': "('BAAR','BAAA'),('CAAR','CAAA')"}
d2 = {k: zip(*ast.literal_eval(v))[0] for k,v in d.iteritems()}
# d2 is now {'FOO': ('BAR', 'CAR'), 'FOOO': ('BAAR', 'CAAR')}
Upvotes: 3