简体   繁体   English

使用列表中的值遍历字典

[英]Iterating through a dictionary using values from a list

I'm working with some data that has ever-changing keys for each record. 我正在处理一些数据,这些数据的每个记录都有不断变化的键。 I've collected a master list of keys from every record and stored them in a list. 我已经从每条记录中收集了一个主键列表,并将它们存储在列表中。 I'd like to then iterate through the list to pull the appropriate values using a try catch but I'm getting an error due to the item in the list item being a str and the dictionary being a dict . 然后,我想遍历列表以使用try catch拉取适当的值,但是由于列表项中的项目为str而字典为dict

An example, notice the possibility of nested keys. 例如,请注意嵌套键的可能性。 Otherwise my approach would be much simpler: 否则我的方法会简单得多:

records = [{
  "id": 2017215,
  "name": "foo bar"
  "campaign": {
    "id": 161,
    "name": "Historical Data Campaign"
  }
},
{
  "id": 2017215,
  "name": "foo bar",
  "last_updated": "2018-01-01",
  "campaign": {
    "id": 161,
    "name": "Historical Data Campaign"
  }
}]

keys = [ ['id'], ['name'], ['campaign'], ['campaign']['id'], ['campaign']['name'], ['last_updated'] ]

for record in records:
  for key in keys:
    print (record + key) # assumption was this would generate "record['id']" but errors due to mismatched types.

Am I making this harder than it needs to be? 我是否正在使它变得比所需的难? The biggest issue is the keys can change from record to record, and in some cases there are nested keys in the data. 最大的问题是密钥可以在记录之间变化,并且在某些情况下,数据中存在嵌套的密钥。

First, you can make the above snippet work if you did something along the lines of 首先,如果您按照以下方式进行操作,则可以使上述代码段起作用

records = # ...
keys = [ ('id',), ('name',), ('campaign',), ('campaign', 'id'), ('campaign', 'name'), ('last_updated',) ]

for record in records:
    for key_tuple in keys:
        obj = record
        for key in key_tuple:
            obj = record[key]
        print(obj)

One issue from your snippet is the occurrence of elements like ['campaign']['id'] . 您的摘要中的一个问题是['campaign']['id']类的元素的出现。 Python assumes the ['campaign'] part is a literal list definition, and then the ['id'] is indexing that list (but can't because it's not an integer). Python假定['campaign']部分是文字列表定义,然后['id']为该列表建立索引(但不能,因为它不是整数)。

More generally, I would suggest looking into the .items() method for dictionaries. 更笼统地说,我建议研究.items()方法来查找字典。 You could turn the above snippet into 您可以将以上代码片段转换为

for record in records:
    for key, value in record.items():

        # to handle nested dictionaries
        if isinstance(value, dict):
            for subkey, subval in value.items():
                print(subkey, subval)
        else:
            print(key, val)

That will handle any keys, but if you have deeper than two levels of nested dictionaries, you may want to re-implement it as a recursive function. 这样可以处理所有键,但是如果嵌套字典的层次超过两个级别,则可能需要将其重新实现为递归函数。

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

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