سؤال

I want to filter out last value in tuple in list of dictionaries. For example

X = [{'a': (123, 12445), 'b': (234, 34)}, {'a': (45666, 4), 'b': (3, 12)}]

to

Y = [{'a':  123, 'b': 234}, {'a': 45666, 'b': 3} ]

My attempt:

[{ j: i[j][0] } for j in i.keys() for i in result ]

But I get this:

[{'a': 123}, {'a': 45666}, {'b': 234}, {'b': 3}]

Any help?

هل كانت مفيدة؟

المحلول

Edit:

Dictionary comprehensions only work in Python 2.7+. Since you are on Python 2.6, you can use dict with a generator expression:

>>> X = [{'a': (123, 12445), 'b': (234, 34)}, {'a': (45666, 4), 'b': (3, 12)}]
>>> [dict((k, v[0]) for k,v in x.iteritems()) for x in X]
[{'b': 234, 'a': 123}, {'b': 3, 'a': 45666}]
>>>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top