Switch key value in dictionary python

Say I have a dictionary like so:

my_dict = {2:3, 5:6, 8:9}

Is there a way that I can switch the keys and values to get:

{3:2, 6:5, 9:8}

asked Nov 29, 2011 at 3:36

2

For Python 3:

my_dict2 = {y: x for x, y in my_dict.items[]}

For Python 2, you can use

my_dict2 = dict[[y, x] for x, y in my_dict.iteritems[]]

Nico Schlömer

48.5k24 gold badges185 silver badges223 bronze badges

answered Nov 29, 2011 at 3:39

GWWGWW

41.9k11 gold badges110 silver badges106 bronze badges

8

my_dict = { my_dict[k]:k for k in my_dict}

Ingo Karkat

163k15 gold badges237 silver badges309 bronze badges

answered Jul 19, 2016 at 11:21

VladEgVladEg

1411 silver badge2 bronze badges

1

Try this:

my_dict = {2:3, 5:6, 8:9}

new_dict = {}
for k, v in my_dict.items[]:
    new_dict[v] = k

answered Nov 29, 2011 at 3:40

Óscar LópezÓscar López

227k35 gold badges303 silver badges377 bronze badges

Use this code [trivially modified] from the accepted answer at Python reverse / invert a mapping:

dict[[v,k] for k, v in my_dict.iteritems[]]

Note that this assumes that the values in the original dictionary are unique. Otherwise you'd end up with duplicate keys in the resulting dictionary, and that is not allowed.

And, as @wim points out, it also assumes the values are hashable. See the Python glossary if you're not sure what is and isn't hashable.

answered Nov 29, 2011 at 3:41

TrottTrott

61.8k22 gold badges159 silver badges201 bronze badges

0

maybe:

flipped_dict = dict[zip[my_dict.values[], my_dict.keys[]]]

answered Nov 29, 2011 at 3:41

aaronaaron

1,06812 silver badges14 bronze badges

3

First of all it is not guaranteed that this is possible, since the values of a dictionary can be unhashable.

In case these are not, we can use a functional approach with:

reversed_dict = dict[map[reversed, original_dict.items[]]]

answered Jan 19, 2018 at 10:25

Willem Van OnsemWillem Van Onsem

409k29 gold badges389 silver badges511 bronze badges

Sometimes, the condition that the values are all unique will not hold, in which case, the answers above will destroy any duplicate values.

The following rolls the values that might be duplicates up into a list:

from itertools import count
dict[[[a,[list[d.keys[]][i] for i,j in zip[count[], d.values[]]if j==a in set[d.values[]]]]

I'm sure there's a better [non-list-comp] method, but I had a problem with the earlier answers, so thought I'd provide my solution in case others have a similar use-case.

P.S. Don't expect the dict to remain neatly arranged after any changes to the original! This method is a one-time use only on a static dict - you have been warned!

answered Jul 29, 2016 at 20:48

Thomas KimberThomas Kimber

9,5562 gold badges23 silver badges41 bronze badges

If the values are not unique this will collide the key space in conversion. Best is to keep the keys in list when switching places

below handles this -

RvsD = dict[]
for k,v in MyDict.iteritems[]:
    RsvD.setdefault[v, []].append[k]

answered Dec 23, 2018 at 3:56

mungayreemungayree

3131 silver badge11 bronze badges

You can do it like this:

Function:

def inverse_dict[my_dict]:
    updated_dict = {}

for i in my_dict:
    updated_dict[my_dict[i]] = [i]

return updated_dict

Main[]:

def main[]:
    year = {'day': 15, 'month': 3, 'year': 2019}
    print[inverse_dict[year]]

if __name__ == "__main__":
    main[]

Ouput:

{15: ['day'], 3: ['month'], 2019: ['year']}

answered Mar 15, 2019 at 12:26

If values are not unique in the dictionary, then you can map keys to that value. Here an example of how to do it using defaultdict

from collections import defaultdict


def reverse_dict[data: dict] -> dict:
    rd = defaultdict[list]
    for k, v in data.items[]:
        rd[v].append[k]
    return rd


if __name__ == "__main__":
    from collections import Counter

    data = "aaa bbb ccc ddd aaa bbb ccc aaa"
    c = Counter[data.split[]]
    print[c]
    # Counter[{'aaa': 3, 'bbb': 2, 'ccc': 2, 'ddd': 1}]
    rd = reverse_dict[c]
    print[rd]
    # defaultdict[, {3: ['aaa'], 2: ['bbb', 'ccc'], 1: ['ddd']}]

answered Jun 23, 2019 at 11:55

Vlad BezdenVlad Bezden

75.6k23 gold badges235 silver badges174 bronze badges

How do you flip a key and value in Python?

Swap dictionary keys and values in Python.
d = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'} d_swap = {v: k for k, v in d. ... .
def get_swap_dict[d]: return {v: k for k, v in d..

Can you change the value of a key in dictionary Python?

dict has no method to change the key, so add a new item with the new key and the original value, and then remove the old item.

Can we update the value of a key in dictionary?

Note: The update[] method adds element[s] to the dictionary if the key is not in the dictionary. If the key is in the dictionary, it updates the key with the new value.

Chủ Đề