简体   繁体   中英

How to get a value using Python list comprehension on a list of OrderedDicts

I have a list called catalogue given to me like this:

[OrderedDict([(u'catalogue_id', 240)]), OrderedDict([(u'catalogue_id', 240)])]

I need to create a new list of ID 's from above. This is what I have tried:

x = [x.catalogue_id for x in catalogue]

But I get the error:

'OrderedDict' object has no attribute 'catalogue_id'. 

I assume this is because it is a list of dicts, how can this be done?

Ordered Dictionaries are subclasses of dictionaries, as such they behave just like ordinary dictionaries when accessing elements. Use key access x['catalogue_id'] for every element in catalogue to access the values:

from collections import OrderedDict

catalogue = [OrderedDict([(u'catalogue_id', 240)]), OrderedDict([(u'catalogue_id', 240)])]

x = [x['catalogue_id'] for x in catalogue]

print(x) # [240, 240]

Note: You might be confusing it with namedtuples which support named dot . access to their elements.

You access the content of a dictionary with __getitem__ , not with __getattribute__ , ie you need to use the bracket notation instead of the dot notation.

>>> a=[OrderedDict([(u'catalogue_id', 240)]), OrderedDict([(u'catalogue_id', 240)])]
>>> [d['catalogue_id'] for d in a]
[240, 240]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM