用列表中的字典附加字典列表(圆形?)

时间:2019-05-23 13:53:10

标签: python

我试图遍历字典列表并搜索特定的键。如果该键的值与特定值匹配,则将提供另一个词典列表。我想在字典的原始列表上附加新的字典。

def test():
    info = [{'a': '1', 'b': '2'}, {'a': '3', 'b': '4'}]
    for item in info:
        if "1" in item['a']:
            info2 = [{'c': '1', 'd': '2'}, {'c': '3', 'd': '4'}]
            for dict in info2:
                info.append(dict)

我希望以上尝试会导致原始信息列表如下:

info = [{'a': '1', 'b': '2'}, {'a': '3', 'b': '4'}, {'c': '1', 'd': '2'}, {'c': '3', 'd': '4'}]

但是我最终以TypeErrors结尾:

TypeError: string indices must be integers.

在此先感谢您的帮助

1 个答案:

答案 0 :(得分:1)

代码中的某些问题

  • 您正在尝试修改要迭代的info列表,而应该通过info来迭代for item in info[:]:的副本
  • 您可以将item['a']更改为item.get('a'),以确保如果不存在密钥,则获取项不会出现异常,并且可以更改为相等
  • 您可以通过使用info2扩展列表,将info列表中的字典添加到list.extend列表中。

那么您的更新代码将是

def test():
    info = [{'a': '1', 'b': '2'}, {'a': '3', 'b': '4'}]
    #Iterate on copy of info
    for item in info[:]:
        #If value of a equals 1
        if item.get('a') == '1':
            #Extend the original list
            info2 = [{'c': '1', 'd': '2'}, {'c': '3', 'd': '4'}]
            info.extend(info2)

    return info

print(test())

输出将是

[
{'a': '1', 'b': '2'}, 
{'a': '3', 'b': '4'}, 
{'c': '1', 'd': '2'}, 
{'c': '3', 'd': '4'}
]