Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Extract values from a Python list

Writer Olivia Zamora

How can I iterate through and extract values from the following list, the code I am using below only gets the key values.

> [{'filename': <docxtpl.InlineImage object at 0x040038D0>, 'desc':
> u'dfgdgfdfg'}, {'filename': <docxtpl.InlineImage object at
> 0x04014930>, 'desc': u'dfgdfgdfg'}, {'filename': <docxtpl.InlineImage
> object at 0x04014A90>, 'desc': u'fghfghfh'}]

Code:

for k,v in audit_items_list: print audit_items_list print k print v

If I use k.value(). I get the following error :

AttributeError: 'str' object has no attribute 'values'

Update:Thanks for all the help, but i actually want to grab the values of filename and desc on each iteration...

3

4 Answers

The outer item is a list, and the inner items are dictionaries. You just need to go one level deeper.

for audit_item in audit_items_list: for k, v in audit_item.items(): # iterate over key value pairs. # Or get the entire list of each by doing item.keys() or item.values()

Use audit_items_list.items() if you are using Python 3 or audit_items_list.iteritems() if you are using Python 2.

2
for tdict in audit_items_list: # To iterate over all dictionaries present in the list # print tdict for key in tdict: # To iterate over all the keys in current dictionary # print key print tdict[key] # To get the value corresponding to that key

Clearly, this is a list of dictionaries where every dictionary has one key-value pair.

for item in audit_items_list: (key, val) = item.items() print(key,value)

Hope this helps!

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy