1

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
  • Is audit_items_list a {} or [{}]? Did you try iteritems()? Commented Feb 26, 2018 at 3:54
  • You have to iterate twice: over the list and over the dicts inside to print all values. Commented Feb 26, 2018 at 3:55
  • list is created using audit_items_list.append({ 'desc' : kwargs["audit_d_pc_{}".format(i)], 'filename' : photo_embed}) Commented Feb 26, 2018 at 3:57

4 Answers 4

2

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()
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

AttributeError: 'list' object has no attribute 'iteritems'
audit_items_list is a list.
1
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

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.