[英]Using multiple loops to make a permutation of the values in a dictionary
我有两本字典。 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
:B
中的所有values
都是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()))]
B
中的values
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()))]
您不需要A
,只需要您想要迭代的值,并使用itertools.product
:
from itertools import product
items = ['A', 'B', 'C']
status = [1, 2, 3]
for i, s in product(items, status):
print({'format': 'json',
'items' : i,
'status' : s,
'name': 'test'})
输出
{'format': 'json', 'items': 'A', 'status': 1, 'name': 'test'}
{'format': 'json', 'items': 'A', 'status': 2, 'name': 'test'}
{'format': 'json', 'items': 'A', 'status': 3, 'name': 'test'}
{'format': 'json', 'items': 'B', 'status': 1, 'name': 'test'}
{'format': 'json', 'items': 'B', 'status': 2, 'name': 'test'}
{'format': 'json', 'items': 'B', 'status': 3, 'name': 'test'}
{'format': 'json', 'items': 'C', 'status': 1, 'name': 'test'}
{'format': 'json', 'items': 'C', 'status': 2, 'name': 'test'}
{'format': 'json', 'items': 'C', 'status': 3, 'name': 'test'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.