python - 使用多个循环对字典中的值进行排列
问题描述
我有两本词典。A
是空B
的,是我想要输入的字典A
,但我应该在不同的循环中输入不同的值。
A = {'format': None,
'items' : None,
'status' : None,
'name': None}
B = {'format': 'json',
'items' : ['A', 'B', 'C'],
'status' : [1, 2, 3],
'name': 'test'}
我有一个愚蠢的方法来得到这个答案,但实际上我想要这样的东西:
while not finish:
for key, values in B.items():
if type(values) != list:
A[key] = values
else :
for items in values:
A[key] = items
# do something here
但这似乎无法达到我想要的目标,即:
A-1,A-2,A-3,B-1,B-2,B-3 ... C-3
第一次迭代:
A = {'format': 'json',
'items' : 'A',
'status' : 1,
'name': 'test'}
第二次迭代:
A = {'format': 'json',
'items' : 'A',
'status' : 2,
'name': 'test'}
等等...
最终迭代:
A = {'format': 'json',
'items' : 'C',
'status' : 3,
'name': 'test'}
解决方案
使用pandas
:
如B
问题所示:
import pandas as pd
from itertools import product
B = {'format': ['json'],
'items' : ['A', 'B', 'C'],
'status' : [1, 2, 3],
'name': ['test']}
df = pd.DataFrame(product(*(v for _, v in B.items())), columns=B.keys())
现在数据的形式可用于进一步分析:
format items status name
0 json A 1 test
1 json A 2 test
2 json A 3 test
3 json B 1 test
4 json B 2 test
5 json B 3 test
6 json C 1 test
7 json C 2 test
8 json C 3 test
数据可以很容易地保存到文件中:
df.to_json('test.json')
{'format': {0: 'json', 1: 'json', 2: 'json', 3: 'json', 4: 'json', 5: 'json', 6: 'json', 7: 'json', 8: 'json'},
'items': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B', 5: 'B', 6: 'C', 7: 'C', 8: 'C'},
'name': {0: 'test', 1: 'test', 2: 'test', 3: 'test', 4: 'test', 5: 'test', 6: 'test', 7: 'test', 8: 'test'},
'status': {0: 1, 1: 2, 2: 3, 3: 1, 4: 2, 5: 3, 6: 1, 7: 2, 8: 3}}
数据可以读回:
df1 = pd.read_json('test.json')
有list comprehension
- 没有pandas
:
如果所有内容values
都是:B
lists
B = {'format': ['json'],
'items' : ['A', 'B', 'C'],
'status' : [1, 2, 3],
'name': ['test']}
list_dicts = [dict(zip(B.keys(), x)) for x in product(*(v for _, v in B.items()))]
如果values
是:B
_str
B = {'format': 'json',
'items' : ['A', 'B', 'C'],
'status' : [1, 2, 3],
'name': 'test'}
list_dicts = [dict(zip(B.keys(), x)) for x in product(*([v] if type(v) == str else v for _, v in B.items()))]
推荐阅读
- android-recyclerview - 约束布局内的Recyclerview
- hybris - 如何本地化在 Hybris 的 trainingcore-items.xml 中创建的自定义类型?
- octave - 尝试计算向量的平均值时的八度越界错误
- live-streaming - 全球服务器上的 Jetson Nano 远程桌面
- dynamics-crm - Dynamics CRM 和 ADF 管道域
- visual-studio-code - 节点不在 vs 代码的集成终端中运行
- php - 在 Codeigniter 中创建备份 Zip 文件,但在 PhpmyAdmin 中导入此文件时,它不会导入
- java - 带有 Ant 的 Netbeans 12 如何更改默认 lib 文件夹
- hosting - “ea-php73”没有“CLI”二进制文件,使用默认...
- python - 如何在 Python Heatmap 中添加矩形补丁?