在字典python中翻转键和值

时间:2015-07-09 19:04:26

标签: python dictionary

我有一个名为z的字典,看起来像这样

{0:[0.28209479177387814,0.19947114020071635,0.10377687435514868,0.07338133158686996], -1:[0.28209479177387814,0.19947114020071635,0.10377687435514868,0.07338133158686996]}。

我想翻转值和键

{0.28209479177387814:0,0.19947114020071635:0,0.10377687435514868:0,0.07338133158686996:0, 0.28209479177387814:-1,0.19947114020071635:-1,0.10377687435514868:-1,0.07338133158686996:-1}

似乎有用的代码是:

for a in z:
     newdict=dict.fromkeys(z[a],a)

但它只适用于z中的一个键并返回:

{0.28209479177387814:-1,0.07338133158686996:-1,0.10377687435514868:-1,0.19947114020071635:-1}

我做错了什么?

3 个答案:

答案 0 :(得分:3)

正如您在关于您的问题的评论中已经看到的那样,Python词典不能有重复键,因为给定键的正确单值会存在不确定性

这可以通过与第一个具有并行结构来解决,因此{value:key}代替{value:[key1, key2]}而不是new = {} for key, value in z.items(): if not value in new: new[value] = [] new[value].append(key) 。生成它的代码是:

stringstream

有关详细信息,请参阅Adam Smith的答案。

答案 1 :(得分:1)

您不能在字典中使用重复键,但可以使用元组以有意义的方式将它们组合在一起。

from itertools import product, chain

tuples = chain.from_iterable(product(vs, [k]) for k, vs in orig_dict.items())
# note this is identical to:
# # tuples = []
# # for k, vs in orig_dict.items():
# #     for tup in [(v, k) for v in vs]:
# #         tuples.append(tup)

这会产生:

[(0.28209479177387814, 0), (0.19947114020071635, 0),
 (0.10377687435514868, 0), (0.07338133158686996, 0),
 (0.28209479177387814, -1), (0.19947114020071635, -1),
 (0.10377687435514868, -1), (0.07338133158686996, -1)]

现在,如果你真的想要一些有趣的东西,你可以对它进行排序并将它们组合在一起。

from itertools import groupby

groups = groupby(sorted(tuples), key=lambda kv: kv[0])

创造了类似的东西:

[(0.07338133158686996, [(0.07338133158686996, 0,
                         0.07338133158686996, -1] ),
 ... ]

你可以通过以下方式将这些投入dict:

final_dict = {k: [v[1] for v in vs] for k, vs in groups}

最终应该给出:

{0.07338133158686996: [0, -1],
 ... }

答案 2 :(得分:0)

在dict中翻转键值的最简单方法是使用dict理解,它是这样的:{value: key for key, value in ORIGINAL_DICT.items()}。完整示例:

REGION_PREFIX = {
    'AB': 'Alberta',
    'BC': 'British Columbia',
    'IN': 'International',
    'MB': 'Manitoba',
    'NB': 'New Brunswick',
    'NL': 'Newfoundland',
    'NS': 'Nova Scotia',
    'NU': 'Nunavut',
    'NW': 'Northwest Territories',
    'ON': 'Ontario',
    'PE': 'Prince Edward Island',
    'QC': 'Quebec',
    'SK': 'Saskatchewan',
    'US': 'United States',
    'YK': 'Yukon',
}

REGION_PREFIX2 = {value: key for key, value in REGION_PREFIX.items()}

您的输出是这样的:

{'Alberta': 'AB', 'British Columbia': 'BC', 'International': 'IN', 'Manitoba': 'MB', 'New Brunswick': 'NB', 'Newfoundland': 'NL', 'Nova Scotia': 'NS', 'Nunavut': 'NU', 'Northwest Territories': 'NW', 'Ontario': 'ON', 'Prince Edward Island': 'PE', 'Quebec': 'QC', 'Saskatchewan': 'SK', 'United States': 'US', 'Yukon': 'YK'}

干杯!