首页 > 解决方案 > 使用多个循环对字典中的值进行排列

问题描述

我有两本词典。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'}

标签: pythondictionary

解决方案


使用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都是:Blists

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()))]

推荐阅读