在Python字典中获取键/值对的所有组合 [英] Getting all combinations of key/value pairs in Python dict

查看:106
本文介绍了在Python字典中获取键/值对的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但要注意以下几点:

This may be a silly question, but given the following dict:

combination_dict = {"one": [1, 2, 3], "two": [2, 3, 4], "three": [3, 4, 5]}

我将如何获得此列表:

result_list = [{"one": [1, 2, 3], "two": [2, 3, 4]}, {"one": [1, 2, 3], "three": [3, 4, 5]}, {"two": [2, 3, 4], "three": [3, 4, 5]}]

换句话说,我希望字典中两个键/值对的所有组合都不能替换,而与顺序无关.

In other words, I want all combinations of two key/value pairs in a dict without replacement, irrespective of order.

推荐答案

一种解决方案是使用itertools.combinations():

result_list = map(dict, itertools.combinations(
    combination_dict.iteritems(), 2))

编辑:由于

Edit: Due to popular demand, here a Python 3.x version:

result_list = list(map(dict, itertools.combinations(
    combination_dict.items(), 2)))

这篇关于在Python字典中获取键/值对的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆