【问题标题】:Adding keys to dicts within a list, from values in a list从列表中的值向列表中的字典添加键
【发布时间】:2018-03-27 21:53:39
【问题描述】:

如果字典包含某个键,我如何从另一个列表中的值向列表中的字典添加键?

我有一个字典列表。这些字典要么只包含一个键('review'),要么包含两个键('review' 和 'response')。当 dict 包含键“响应”时,我想添加两个键,其值来自两个列表。

data = [{'response': 'This is a response',
         'review': 'This is a review'},
        {'review': 'This is only a review'},
        {'response': 'This is also a response',
         'review': 'This is also a review'}]
date = ['4 days ago',
        '3 days ago']
responder = ['Manager',
             'Customer service']

我尝试了以下方法,但是由于对于每个包含键“响应”的 dict,我只想从每个列表的值中添加 1,因此我不确定如何执行此操作。

for d in data:
    if 'response' in d:
        for i in date:
            d['date'] = i
        for i in responder:
            d['responder'] = i

输出告诉我它当然只添加了列表的最后一个值,因为我正在循环遍历列表。我该如何解决这个问题?

[{'date': '3 days ago',
  'responder': 'Customer service',
  'response': 'This is a response',
  'review': 'This is a review'},
 {'review': 'This is only a review'},
 {'date': '3 days ago',
  'responder': 'Customer service',
  'response': 'This is also a response',
  'review': 'This is also a review'}]

【问题讨论】:

  • 您如何决定应该将dateresponder 中的哪一项作为值添加到字典中?
  • responses、dates和responers同时被抓取和解析,所以第一个有response的review属于第一个date和first responder。
  • 请您提供预期的输出!

标签: python list loops dictionary key


【解决方案1】:

我认为您正在尝试添加两个条目,其中 Date 作为键和值是不同的。在字典中,您不能有重复的键。这就是为什么在 for 循环字典更新后只有一个 Date 键条目和一个响应者条目

【讨论】:

    【解决方案2】:

    您可以为您的日期和响应者列表创建一个迭代器,然后在 if 语句中调用 next() 以从列表中获取下一项

    data = [{'response': 'This is a response', 
             'review': 'This is a review'}, 
    
            {'review': 'This is only a review'}, 
    
            {'response': 'This is also a response', 
             'review': 'This is also a review'}]
    
    date = ['4 days ago', '3 days ago']
    responder = ['Manager', 'Customer service']
    
    d_iter = iter(date)
    r_iter = iter(responder)
    
    for d in data:
        if 'response' in d:
            d['date'] = next(d_iter)
            d['responder'] = next(r_iter)
    
    print(data)
    >> [
    {'date': '4 days ago', 
     'review': 'This is a review', 
     'responder': 'Manager', 
     'response': 'This is a response'},  
    
    {'review': 'This is only a review'}, 
    
    {'date': '3 days ago', 
     'review': 'This is also a review', 
     'responder': 'Customer service', 
     'response': 'This is also a response'}
    ]
    

    【讨论】:

    • 干得好。我使用生成器解决了这个问题,但iternext 组合比for 循环更干净。
    【解决方案3】:

    你可以试试这个,但要小心,因为你列表中response的数量应该等于你列表的长度:

    d_r = zip(date, responder)
    
    for d in data:
        if 'response' in d:
                d['date'], d['responder'] = next(d_r)
    print(data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      相关资源
      最近更新 更多