python - 在python中使用for循环从其他dicts创建dict
问题描述
从现有字典中获取不同字典的好方法是什么?
例如我有这个:
x = {"x1":1,"x2":2,"x3":3}
y = {"y1":1,"y2":2,"y3":3}
z = {"z1":1,"z2":2,"z3":3}
我想要这个:
dict1 = {"x1":1,"y1":1,"z1":1}
dict2 = {"x2":2,"y2":2,"z2":2}
dict3 = {"x3":3,"y3":3,"z3":3}
假设我有更多的数据,我想要一个高效的快速方法,比如循环。
解决方案
您可以使用zip
来实现这一点 -
a, b, c = [i for i in zip(x.items(), y.items(), z.items())]
dict1, dict2, dict3 = dict(a), dict(b), dict(c)
print(dict1)
print(dict2)
print(dict3)
{'x1': 1, 'y1': 1, 'z1': 1}
{'x2': 2, 'y2': 2, 'z2': 2}
{'x3': 3, 'y3': 3, 'z3': 3}
编辑:正如@Moinuddin 正确指出的那样,您可以通过将类型转换映射到 zip 对象来将其写在一行中。
dict1, dict2, dict3 = map(dict, zip(x.items(), y.items(), z.items()))
推荐阅读
- bixby - 如何检查 Bixby 布局视图中是否存在文本值内容
- php - PDOException: SQLSTATE[HY000] [2002] 操作正在进行,在 php artisan queue:work
- swagger - MicroElements.Swashbuckle.FluentValidation AddFluentValidationRules 使用命令处理程序模式
- php - 未使用 phpSpreadSheet 库在现有工作簿中创建新工作表
- angular - 如何在角度项目中调整 kendo Splitter 的活动大小?
- ios - 具有关联值的枚举数据模型
- java - Openssl 公钥\私钥跨操作系统平台支持
- python - 调用使用类中另一个方法的变量的方法
- postgresql - 将 postgresql 数组转换为集合
- android - 从 Play 商店下载应用程序时 Azure MSAL 集成不起作用