switching keys and values in a dictionary in 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}
python dictionary key
add a comment |
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}
python dictionary key
1
Are the values unique? Are the values hashable?
– wim
Nov 29 '11 at 3:45
add a comment |
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}
python dictionary key
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}
python dictionary key
python dictionary key
edited Nov 24 '18 at 11:06
ViAik
5019
5019
asked Nov 29 '11 at 3:36
me45me45
3193714
3193714
1
Are the values unique? Are the values hashable?
– wim
Nov 29 '11 at 3:45
add a comment |
1
Are the values unique? Are the values hashable?
– wim
Nov 29 '11 at 3:45
1
1
Are the values unique? Are the values hashable?
– wim
Nov 29 '11 at 3:45
Are the values unique? Are the values hashable?
– wim
Nov 29 '11 at 3:45
add a comment |
8 Answers
8
active
oldest
votes
my_dict2 = dict((y,x) for x,y in my_dict.iteritems())
If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:
my_dict2 = {y:x for x,y in my_dict.iteritems()}
Edit
As noted in the comments by JBernardo, for python 3.x you need to use items
instead of iteritems
3
.iteritems()
is not valid on Python 3.x...
– JBernardo
Nov 29 '11 at 3:47
@JBernardo: Fixed thanks I forgot about that
– GWW
Nov 29 '11 at 3:48
1
another correction - doing the dictionary comprehension you suggest{(y, x) for x, y in dic_cols_w.items()}
returns a set, not a dictionary. You would still need to wrap this in adict(...)
to get a dictionary
– tsando
Apr 5 '17 at 13:06
3
@tsando: I think you have read my answer incorrectly. I have{y:x ...
– GWW
Apr 5 '17 at 22:34
How would you do this if the values were a list of items and each item in the list should be a key?
– Woody Pride
Feb 6 at 14:49
|
show 1 more comment
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.
add a comment |
Try this:
my_dict = {2:3, 5:6, 8:9}
new_dict = {}
for k, v in my_dict.items():
new_dict[v] = k
add a comment |
maybe:
flipped_dict = dict(zip(my_dict.values(), my_dict.keys()))
2
this is probably not safe as it relies on key and value ordering, although it happened to work for me. I like JBernardo/GWW's answer(s).
– aaron
Nov 29 '11 at 3:43
It's probably better to useiterkeys
anditervalues
– GWW
Nov 29 '11 at 3:44
That's safe if the dict isn't changed during the operation. I liked because you did it without a comprehension.
– JBernardo
Nov 29 '11 at 3:51
add a comment |
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!
add a comment |
my_dict = { my_dict[k]:k for k in my_dict}
add a comment |
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()))
add a comment |
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)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8305518%2fswitching-keys-and-values-in-a-dictionary-in-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
8 Answers
8
active
oldest
votes
8 Answers
8
active
oldest
votes
active
oldest
votes
active
oldest
votes
my_dict2 = dict((y,x) for x,y in my_dict.iteritems())
If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:
my_dict2 = {y:x for x,y in my_dict.iteritems()}
Edit
As noted in the comments by JBernardo, for python 3.x you need to use items
instead of iteritems
3
.iteritems()
is not valid on Python 3.x...
– JBernardo
Nov 29 '11 at 3:47
@JBernardo: Fixed thanks I forgot about that
– GWW
Nov 29 '11 at 3:48
1
another correction - doing the dictionary comprehension you suggest{(y, x) for x, y in dic_cols_w.items()}
returns a set, not a dictionary. You would still need to wrap this in adict(...)
to get a dictionary
– tsando
Apr 5 '17 at 13:06
3
@tsando: I think you have read my answer incorrectly. I have{y:x ...
– GWW
Apr 5 '17 at 22:34
How would you do this if the values were a list of items and each item in the list should be a key?
– Woody Pride
Feb 6 at 14:49
|
show 1 more comment
my_dict2 = dict((y,x) for x,y in my_dict.iteritems())
If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:
my_dict2 = {y:x for x,y in my_dict.iteritems()}
Edit
As noted in the comments by JBernardo, for python 3.x you need to use items
instead of iteritems
3
.iteritems()
is not valid on Python 3.x...
– JBernardo
Nov 29 '11 at 3:47
@JBernardo: Fixed thanks I forgot about that
– GWW
Nov 29 '11 at 3:48
1
another correction - doing the dictionary comprehension you suggest{(y, x) for x, y in dic_cols_w.items()}
returns a set, not a dictionary. You would still need to wrap this in adict(...)
to get a dictionary
– tsando
Apr 5 '17 at 13:06
3
@tsando: I think you have read my answer incorrectly. I have{y:x ...
– GWW
Apr 5 '17 at 22:34
How would you do this if the values were a list of items and each item in the list should be a key?
– Woody Pride
Feb 6 at 14:49
|
show 1 more comment
my_dict2 = dict((y,x) for x,y in my_dict.iteritems())
If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:
my_dict2 = {y:x for x,y in my_dict.iteritems()}
Edit
As noted in the comments by JBernardo, for python 3.x you need to use items
instead of iteritems
my_dict2 = dict((y,x) for x,y in my_dict.iteritems())
If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:
my_dict2 = {y:x for x,y in my_dict.iteritems()}
Edit
As noted in the comments by JBernardo, for python 3.x you need to use items
instead of iteritems
edited Nov 29 '11 at 3:48
answered Nov 29 '11 at 3:39
GWWGWW
33k68796
33k68796
3
.iteritems()
is not valid on Python 3.x...
– JBernardo
Nov 29 '11 at 3:47
@JBernardo: Fixed thanks I forgot about that
– GWW
Nov 29 '11 at 3:48
1
another correction - doing the dictionary comprehension you suggest{(y, x) for x, y in dic_cols_w.items()}
returns a set, not a dictionary. You would still need to wrap this in adict(...)
to get a dictionary
– tsando
Apr 5 '17 at 13:06
3
@tsando: I think you have read my answer incorrectly. I have{y:x ...
– GWW
Apr 5 '17 at 22:34
How would you do this if the values were a list of items and each item in the list should be a key?
– Woody Pride
Feb 6 at 14:49
|
show 1 more comment
3
.iteritems()
is not valid on Python 3.x...
– JBernardo
Nov 29 '11 at 3:47
@JBernardo: Fixed thanks I forgot about that
– GWW
Nov 29 '11 at 3:48
1
another correction - doing the dictionary comprehension you suggest{(y, x) for x, y in dic_cols_w.items()}
returns a set, not a dictionary. You would still need to wrap this in adict(...)
to get a dictionary
– tsando
Apr 5 '17 at 13:06
3
@tsando: I think you have read my answer incorrectly. I have{y:x ...
– GWW
Apr 5 '17 at 22:34
How would you do this if the values were a list of items and each item in the list should be a key?
– Woody Pride
Feb 6 at 14:49
3
3
.iteritems()
is not valid on Python 3.x...– JBernardo
Nov 29 '11 at 3:47
.iteritems()
is not valid on Python 3.x...– JBernardo
Nov 29 '11 at 3:47
@JBernardo: Fixed thanks I forgot about that
– GWW
Nov 29 '11 at 3:48
@JBernardo: Fixed thanks I forgot about that
– GWW
Nov 29 '11 at 3:48
1
1
another correction - doing the dictionary comprehension you suggest
{(y, x) for x, y in dic_cols_w.items()}
returns a set, not a dictionary. You would still need to wrap this in a dict(...)
to get a dictionary– tsando
Apr 5 '17 at 13:06
another correction - doing the dictionary comprehension you suggest
{(y, x) for x, y in dic_cols_w.items()}
returns a set, not a dictionary. You would still need to wrap this in a dict(...)
to get a dictionary– tsando
Apr 5 '17 at 13:06
3
3
@tsando: I think you have read my answer incorrectly. I have
{y:x ...
– GWW
Apr 5 '17 at 22:34
@tsando: I think you have read my answer incorrectly. I have
{y:x ...
– GWW
Apr 5 '17 at 22:34
How would you do this if the values were a list of items and each item in the list should be a key?
– Woody Pride
Feb 6 at 14:49
How would you do this if the values were a list of items and each item in the list should be a key?
– Woody Pride
Feb 6 at 14:49
|
show 1 more comment
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.
add a comment |
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.
add a comment |
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.
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.
edited May 23 '17 at 12:10
Community♦
11
11
answered Nov 29 '11 at 3:41
TrottTrott
37.9k19104152
37.9k19104152
add a comment |
add a comment |
Try this:
my_dict = {2:3, 5:6, 8:9}
new_dict = {}
for k, v in my_dict.items():
new_dict[v] = k
add a comment |
Try this:
my_dict = {2:3, 5:6, 8:9}
new_dict = {}
for k, v in my_dict.items():
new_dict[v] = k
add a comment |
Try this:
my_dict = {2:3, 5:6, 8:9}
new_dict = {}
for k, v in my_dict.items():
new_dict[v] = k
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 '11 at 3:40
Óscar LópezÓscar López
178k25227323
178k25227323
add a comment |
add a comment |
maybe:
flipped_dict = dict(zip(my_dict.values(), my_dict.keys()))
2
this is probably not safe as it relies on key and value ordering, although it happened to work for me. I like JBernardo/GWW's answer(s).
– aaron
Nov 29 '11 at 3:43
It's probably better to useiterkeys
anditervalues
– GWW
Nov 29 '11 at 3:44
That's safe if the dict isn't changed during the operation. I liked because you did it without a comprehension.
– JBernardo
Nov 29 '11 at 3:51
add a comment |
maybe:
flipped_dict = dict(zip(my_dict.values(), my_dict.keys()))
2
this is probably not safe as it relies on key and value ordering, although it happened to work for me. I like JBernardo/GWW's answer(s).
– aaron
Nov 29 '11 at 3:43
It's probably better to useiterkeys
anditervalues
– GWW
Nov 29 '11 at 3:44
That's safe if the dict isn't changed during the operation. I liked because you did it without a comprehension.
– JBernardo
Nov 29 '11 at 3:51
add a comment |
maybe:
flipped_dict = dict(zip(my_dict.values(), my_dict.keys()))
maybe:
flipped_dict = dict(zip(my_dict.values(), my_dict.keys()))
answered Nov 29 '11 at 3:41
aaronaaron
835812
835812
2
this is probably not safe as it relies on key and value ordering, although it happened to work for me. I like JBernardo/GWW's answer(s).
– aaron
Nov 29 '11 at 3:43
It's probably better to useiterkeys
anditervalues
– GWW
Nov 29 '11 at 3:44
That's safe if the dict isn't changed during the operation. I liked because you did it without a comprehension.
– JBernardo
Nov 29 '11 at 3:51
add a comment |
2
this is probably not safe as it relies on key and value ordering, although it happened to work for me. I like JBernardo/GWW's answer(s).
– aaron
Nov 29 '11 at 3:43
It's probably better to useiterkeys
anditervalues
– GWW
Nov 29 '11 at 3:44
That's safe if the dict isn't changed during the operation. I liked because you did it without a comprehension.
– JBernardo
Nov 29 '11 at 3:51
2
2
this is probably not safe as it relies on key and value ordering, although it happened to work for me. I like JBernardo/GWW's answer(s).
– aaron
Nov 29 '11 at 3:43
this is probably not safe as it relies on key and value ordering, although it happened to work for me. I like JBernardo/GWW's answer(s).
– aaron
Nov 29 '11 at 3:43
It's probably better to use
iterkeys
and itervalues
– GWW
Nov 29 '11 at 3:44
It's probably better to use
iterkeys
and itervalues
– GWW
Nov 29 '11 at 3:44
That's safe if the dict isn't changed during the operation. I liked because you did it without a comprehension.
– JBernardo
Nov 29 '11 at 3:51
That's safe if the dict isn't changed during the operation. I liked because you did it without a comprehension.
– JBernardo
Nov 29 '11 at 3:51
add a comment |
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!
add a comment |
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!
add a comment |
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!
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 '16 at 20:48
Thomas KimberThomas Kimber
3,36921323
3,36921323
add a comment |
add a comment |
my_dict = { my_dict[k]:k for k in my_dict}
add a comment |
my_dict = { my_dict[k]:k for k in my_dict}
add a comment |
my_dict = { my_dict[k]:k for k in my_dict}
my_dict = { my_dict[k]:k for k in my_dict}
edited Jul 19 '16 at 11:39
Ingo Karkat
132k14148199
132k14148199
answered Jul 19 '16 at 11:21
VladEgVladEg
111
111
add a comment |
add a comment |
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()))
add a comment |
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()))
add a comment |
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()))
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 '18 at 10:25
Willem Van OnsemWillem Van Onsem
148k16142232
148k16142232
add a comment |
add a comment |
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)
add a comment |
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)
add a comment |
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)
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 '18 at 3:56
mungayreemungayree
1118
1118
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8305518%2fswitching-keys-and-values-in-a-dictionary-in-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Are the values unique? Are the values hashable?
– wim
Nov 29 '11 at 3:45