【问题标题】:Unpacking a list of dictionaries based on key matches in Python根据 Python 中的键匹配解包字典列表
【发布时间】:2015-05-11 13:17:25
【问题描述】:

我正在寻找一种方法来解压具有特定密钥 ID 的字典列表。我已经看到了很多基于键值的示例,但没有任何关于键匹配的示例。假设我有一个从函数返回的以下格式的字典...

data = [{'Lev1': u'82', 'Marker': u'16', 'TYPE': u'139', 'Location': u'A'},
        {'Lev2': u'652', 'Marker': u'1', 'TYPE': u'140', 'Location': u'C'},
        {'Lev3': u'452', 'Marker': u'188', 'TYPE': u'141', 'Location': u'B'}]

我当前的尝试如下所示,但我得到 >> TypeError: list indices must be integers, not str

for item in data:
    parts[data['TYPE']].update(data)

上面的parts 参考是零件编号字典。我希望根据TYPE 将以下每个列表条目(例如'Lev1': u'82', 'Marker': u'16', 'TYPE': u'139', 'Location': u'A')放入主“部分”字典中(parts 字典中应该已经有一个类型匹配)。

我的方法适用于单个返回的字典条目...

parts[data['TYPE']].update(data)

...但只是没有字典列表。

我希望最终得到一种类似于...的格式

parts{
    125:
    ...
    ...
    ...
    139:{
        'Lev1': u'82', 
        'Marker': u'16', 
        'TYPE': u'139', 
        'Location': u'A'
        plus other previously gathered data
        }

    140:{
        'Lev2': u'652', 
        'Marker': u'1', 
        'TYPE': u'140', 
        'Location': u'C'
        plus other previously gathered data
        }

    141:{
        'Lev3': u'452', 
        'Marker': u'188', 
        'TYPE': u'141', 
        'Location': u'B'
        plus other previously gathered data
        }
    142:etc
    ...
}

【问题讨论】:

  • 你的预期输出是什么?
  • 您正在索引列表data 不是字典,但parts[item['TYPE']].update(data) 也不起作用,除非每个键都存在
  • @MikG,添加部分字典
  • 什么版本的 Python?

标签: python dictionary


【解决方案1】:

您可以用item 代替data update

for item in data:
    parts[item['TYPE']].update(item)

结果

>>> parts
{'141': {'Lev3': '452', 'TYPE': '141', 'Marker': '188', 'Location': 'B'},
 '140': {'Lev2': '652', 'TYPE': '140', 'Marker': '1', 'Location': 'C'},
 '139': {'Lev1': '82', 'Marker': '16', 'Location': 'A', 'TYPE': '139'}}

【讨论】:

  • 感谢@Cyber​​ 的帖子,我想我的思路是正确的。再次感谢您的帮助
【解决方案2】:

我认为这就是您想要的,使用 item['TYPE'] 作为关键匹配。你应该使用item 而不是data

for item in data:
    if isinstance(parts, dict):
        # when there is a dictionary in parts with key=item['TYPE'], update it
        if parts.get(item['TYPE']):
            parts[item['TYPE']].update(item)
        # when there is nothing in parts with key=item['TYPE'], add item to it
        else:
            parts[item['TYPE']]=item

【讨论】:

    【解决方案3】:

    'TYPE' 不是data 的索引。它是列表data 中字典item 的键。你可以这样做:

    for item in data:
        if item['TYPE'] in parts:
            parts[item['TYPE']].update(item)
        else:
            parts[item['TYPE']]=item
    

    【讨论】:

      猜你喜欢
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 2021-01-10
      • 2021-11-17
      • 1970-01-01
      • 2021-07-26
      相关资源
      最近更新 更多