首页 > 解决方案 > 使用列表中的字典附加字典列表(圆形?)

问题描述

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

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.

提前感谢您的任何帮助

标签: python

解决方案


您的代码中的一些问题

  • 您正在尝试修改您正在迭代的列表,而不是您应该迭代viainfo的副本infofor item in info[:]:
  • 如果密钥不存在,您可以更改item['a']item.get('a')确保获取项目不会出现异常,并且您可以更改为相等
  • 您可以通过使用扩展列表将字典从info2列表添加到列表infolist.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'}
]

推荐阅读