![](/img/trans.png)
[英]How do I pair up multiple keys with one values from a dictionary through a function?
[英]How do I iterate through a dictionary of lists and pair each iteration with an item from all the keys?
我需要遍历列表字典,不知道字典将有多少列表,但仍然将每个列表值与字典中另一个键生成的任何其他列表值配对(如果存在另一个键)。 我有以下代码:
def loop_rec(codes, currentcode={}):
if len(codes.keys())>1:
for key in sorted(codes):
codespop = dict(codes)
loop = codespop.pop(key)
for x in loop:
currentcode[key]=x
loop_rec(codespop,currentcode)
break
else:
for key in codes.keys():
loop = codes[key]
for x in loop:
currentcode[key]=x
print currentcode
所以,如果我有以下字典:
codes = {"coarse":range(4),"fine":range(2)}
我得到这个结果:
>>> loop_rec(codes)
{'fine': 0, 'coarse': 0}
{'fine': 1, 'coarse': 0}
{'fine': 0, 'coarse': 1}
{'fine': 1, 'coarse': 1}
{'fine': 0, 'coarse': 2}
{'fine': 1, 'coarse': 2}
{'fine': 0, 'coarse': 3}
{'fine': 1, 'coarse': 3}
这是一种蛮力方法,并希望采用更“Pythonic”的方式。 我搜索了大量相当的东西,但是大多数方法都没有导致粗略和精细值一起用于每次迭代。 也希望它首先循环粗略,但排序的命令不起作用。
编辑:刚刚意识到排序的命令正在工作,打印输出只是没有排序。 我不在乎是否按顺序打印。
如果我正确理解你的问题,你想要把所有列表中的笛卡尔积作为dict的值。 您可以使用itertools.product
来完成此任务。
import itertools
def dict_product(d):
list_of_dicts = []
for values in itertools.product(*d.values()):
item = dict(zip(d.keys(),values))
list_of_dicts.append(item)
return list_of_dicts
codes = {"coarse":range(4),"fine":range(2),"zesty":range(3)}
for item in dict_product(codes):
print(item)
结果:
{'zesty': 0, 'fine': 0, 'coarse': 0}
{'zesty': 0, 'fine': 0, 'coarse': 1}
{'zesty': 0, 'fine': 0, 'coarse': 2}
{'zesty': 0, 'fine': 0, 'coarse': 3}
{'zesty': 0, 'fine': 1, 'coarse': 0}
{'zesty': 0, 'fine': 1, 'coarse': 1}
{'zesty': 0, 'fine': 1, 'coarse': 2}
{'zesty': 0, 'fine': 1, 'coarse': 3}
{'zesty': 1, 'fine': 0, 'coarse': 0}
{'zesty': 1, 'fine': 0, 'coarse': 1}
{'zesty': 1, 'fine': 0, 'coarse': 2}
{'zesty': 1, 'fine': 0, 'coarse': 3}
{'zesty': 1, 'fine': 1, 'coarse': 0}
{'zesty': 1, 'fine': 1, 'coarse': 1}
{'zesty': 1, 'fine': 1, 'coarse': 2}
{'zesty': 1, 'fine': 1, 'coarse': 3}
{'zesty': 2, 'fine': 0, 'coarse': 0}
{'zesty': 2, 'fine': 0, 'coarse': 1}
{'zesty': 2, 'fine': 0, 'coarse': 2}
{'zesty': 2, 'fine': 0, 'coarse': 3}
{'zesty': 2, 'fine': 1, 'coarse': 0}
{'zesty': 2, 'fine': 1, 'coarse': 1}
{'zesty': 2, 'fine': 1, 'coarse': 2}
{'zesty': 2, 'fine': 1, 'coarse': 3}
在此示例中,迭代顺序是粗略精细的,但不保证此行为。 在CPython 3.6及更高版本中,字典是有序的,但这是一个实现细节,将来可能会发生变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.