简体   繁体   English

从 Python 列表中提取值

[英]Extract values from a Python list

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() .如果我使用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...更新:感谢所有的帮助,但我实际上想在每次迭代中获取文件名和 desc 的值......

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()

如果您使用的是 Python 3,请使用audit_items_list.items()如果您使用的是 Python 2,请使用audit_items_list.iteritems()

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!希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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