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.
提前感谢您的任何帮助
解决方案
您的代码中的一些问题
- 您正在尝试修改您正在迭代的列表,而不是您应该迭代via
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'}
]
推荐阅读
- java - 错误:无法创建 Java 虚拟机
- c# - 如何在没有继承属性的情况下在设计时填写列表?
- android - React native:Haste模块映射中不存在模块`DrawerLayoutAndroid`
- sql - 通过使用索引加速使用聚合函数的查询
- ffmpeg - 使用 emscripten 编译 libavcodec(带硬件加速)
- java - 检查端口是否已绑定并在 Java 中侦听;“重置”一个 SocketChannel?
- visual-studio-code - 如何启用 cmd+click(智能感知)并转到 vs 代码中的任何功能?
- go - Gorilla mux,静态文件服务器的中间件
- json - AWS Cloudformation APIGateway 在尝试设置静态标头值时遇到不受支持的属性 IntegrationResponses
- javascript - 带有 document.getElementById 的简单 javascript 从 html 中提取文本