Reverse dictionary where values are listsConvert dictionary of lists of tuples to list of lists/tuples in pythonMulti-dictionary API using Python Flask-RESTfulUpdating a dict with dict valuesMatching two lists of dicts, strictly and more looselyCreate dictionary with default immutable keysDictionary of dictionary - Get 2nd keysList all possible permutations from a python dictionary of listsFlatten Dictionary Python challengeRemove the second number from every group of three numbersTransforming a dict of lists into a list of dicts
Should I tell management that I intend to leave due to bad software development practices?
How writing a dominant 7 sus4 chord in RNA ( Vsus7 chord in the 1st inversion)
What killed these X2 caps?
Could the museum Saturn V's be refitted for one more flight?
Why is it a bad idea to hire a hitman to eliminate most corrupt politicians?
How can saying a song's name be a copyright violation?
Why was the shrinking from 8″ made only to 5.25″ and not smaller (4″ or less)?
Assassin's bullet with mercury
How would I stat a creature to be immune to everything but the Magic Missile spell? (just for fun)
Avoiding direct proof while writing proof by induction
If human space travel is limited by the G force vulnerability, is there a way to counter G forces?
What does “the session was packed” mean in this context?
Im going to France and my passport expires June 19th
Bullying boss launched a smear campaign and made me unemployable
How to tell a function to use the default argument values?
Alternative to sending password over mail?
Is there a hemisphere-neutral way of specifying a season?
Why do bosons tend to occupy the same state?
What mechanic is there to disable a threat instead of killing it?
Can my sorcerer use a spellbook only to collect spells and scribe scrolls, not cast?
Is "remove commented out code" correct English?
How does a predictive coding aid in lossless compression?
Size of subfigure fitting its content (tikzpicture)
Is it inappropriate for a student to attend their mentor's dissertation defense?
Reverse dictionary where values are lists
Convert dictionary of lists of tuples to list of lists/tuples in pythonMulti-dictionary API using Python Flask-RESTfulUpdating a dict with dict valuesMatching two lists of dicts, strictly and more looselyCreate dictionary with default immutable keysDictionary of dictionary - Get 2nd keysList all possible permutations from a python dictionary of listsFlatten Dictionary Python challengeRemove the second number from every group of three numbersTransforming a dict of lists into a list of dicts
$begingroup$
I'm working on the following problem: I've got a dictionary like this one:
dic=0:[0,1,2],1:[3,4,5]
And I want to reverse it so it looks like this:
dic2=0:0,1:0,2:0,3:1,4:1,5:1
I managed to make it, but doing this:
dic2=
for i in dic:
for j in dic[i]:
dic2[j]=i
I know about list and dict comprehensions and this code reeks of it, but I'm not good at them when there are nested for
and dicts
. How would you make it more efficiently?
python dictionary
New contributor
$endgroup$
add a comment |
$begingroup$
I'm working on the following problem: I've got a dictionary like this one:
dic=0:[0,1,2],1:[3,4,5]
And I want to reverse it so it looks like this:
dic2=0:0,1:0,2:0,3:1,4:1,5:1
I managed to make it, but doing this:
dic2=
for i in dic:
for j in dic[i]:
dic2[j]=i
I know about list and dict comprehensions and this code reeks of it, but I'm not good at them when there are nested for
and dicts
. How would you make it more efficiently?
python dictionary
New contributor
$endgroup$
add a comment |
$begingroup$
I'm working on the following problem: I've got a dictionary like this one:
dic=0:[0,1,2],1:[3,4,5]
And I want to reverse it so it looks like this:
dic2=0:0,1:0,2:0,3:1,4:1,5:1
I managed to make it, but doing this:
dic2=
for i in dic:
for j in dic[i]:
dic2[j]=i
I know about list and dict comprehensions and this code reeks of it, but I'm not good at them when there are nested for
and dicts
. How would you make it more efficiently?
python dictionary
New contributor
$endgroup$
I'm working on the following problem: I've got a dictionary like this one:
dic=0:[0,1,2],1:[3,4,5]
And I want to reverse it so it looks like this:
dic2=0:0,1:0,2:0,3:1,4:1,5:1
I managed to make it, but doing this:
dic2=
for i in dic:
for j in dic[i]:
dic2[j]=i
I know about list and dict comprehensions and this code reeks of it, but I'm not good at them when there are nested for
and dicts
. How would you make it more efficiently?
python dictionary
python dictionary
New contributor
New contributor
edited 5 hours ago
Sᴀᴍ Onᴇᴌᴀ
10.1k62167
10.1k62167
New contributor
asked 5 hours ago
Juan CJuan C
1185
1185
New contributor
New contributor
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
$begingroup$
There's really not much to say about this code, it is straightforward.
Style
These are only nitpicks.
- Generic dictionary keys are typically named
k
instead ofi
orj
, but in a specific application a more descriptive name would be even better. - Collections should be named by their purpose in the application, not their type.
- By convention, assignments and other binary operators should be surrounded by spaces:
a = b
, nota=b
. See PEP 8 for reference, if you're not already aware of it. Following this style guide makes your code easier to read for others.
Code improvements
When iterating over the keys and values of a dictionary at the same time, you can use
for k, v in dic.items():
# ... use k, v ...
instead of
for k in dic:
v = dic[k]
# ...
The nested loop can be transformed to a dictionary comprehension like this:
dic2 = v: k for k, values in dic.items() for v in values
You can remember that the order of for
clauses in the comprehension is the same as the order of corresponding nested for
loops.
Potential pitfalls
You should be aware that this transformation from a dictionary of lists to a reverse dictionary only works if all items in the original lists are unique. Counterexample:
>>> dic = 0: [1, 2], 1: [2, 3]
>>> v: k for k, values in dic.items() for v in values
1: 0, 2: 1, 3: 1 # missing 2: 0
To correct this, the output dictionary should have the same format as the input, namely mapping each of the items in the input lists to a list of corresponding keys.
If the input represents a directed graph (mapping nodes to lists of neighbours), this corresponds to computing the transposed or reversed graph. It can be done by using a collections.defaultdict
. I don't see an easy way to write it as a comprehension in this case.
from collections import defaultdict
graph = 0: [1, 2], 1: [2, 3]
transposed_graph = defaultdict(list)
for node, neighbours in graph.items():
for neighbour in neighbours:
transposed_graph[neighbour].append(node)
# 1: [0], 2: [0, 1], 3: [1]
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");
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: "196"
;
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: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
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
);
);
Juan C is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
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%2fcodereview.stackexchange.com%2fquestions%2f216814%2freverse-dictionary-where-values-are-lists%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
There's really not much to say about this code, it is straightforward.
Style
These are only nitpicks.
- Generic dictionary keys are typically named
k
instead ofi
orj
, but in a specific application a more descriptive name would be even better. - Collections should be named by their purpose in the application, not their type.
- By convention, assignments and other binary operators should be surrounded by spaces:
a = b
, nota=b
. See PEP 8 for reference, if you're not already aware of it. Following this style guide makes your code easier to read for others.
Code improvements
When iterating over the keys and values of a dictionary at the same time, you can use
for k, v in dic.items():
# ... use k, v ...
instead of
for k in dic:
v = dic[k]
# ...
The nested loop can be transformed to a dictionary comprehension like this:
dic2 = v: k for k, values in dic.items() for v in values
You can remember that the order of for
clauses in the comprehension is the same as the order of corresponding nested for
loops.
Potential pitfalls
You should be aware that this transformation from a dictionary of lists to a reverse dictionary only works if all items in the original lists are unique. Counterexample:
>>> dic = 0: [1, 2], 1: [2, 3]
>>> v: k for k, values in dic.items() for v in values
1: 0, 2: 1, 3: 1 # missing 2: 0
To correct this, the output dictionary should have the same format as the input, namely mapping each of the items in the input lists to a list of corresponding keys.
If the input represents a directed graph (mapping nodes to lists of neighbours), this corresponds to computing the transposed or reversed graph. It can be done by using a collections.defaultdict
. I don't see an easy way to write it as a comprehension in this case.
from collections import defaultdict
graph = 0: [1, 2], 1: [2, 3]
transposed_graph = defaultdict(list)
for node, neighbours in graph.items():
for neighbour in neighbours:
transposed_graph[neighbour].append(node)
# 1: [0], 2: [0, 1], 3: [1]
$endgroup$
add a comment |
$begingroup$
There's really not much to say about this code, it is straightforward.
Style
These are only nitpicks.
- Generic dictionary keys are typically named
k
instead ofi
orj
, but in a specific application a more descriptive name would be even better. - Collections should be named by their purpose in the application, not their type.
- By convention, assignments and other binary operators should be surrounded by spaces:
a = b
, nota=b
. See PEP 8 for reference, if you're not already aware of it. Following this style guide makes your code easier to read for others.
Code improvements
When iterating over the keys and values of a dictionary at the same time, you can use
for k, v in dic.items():
# ... use k, v ...
instead of
for k in dic:
v = dic[k]
# ...
The nested loop can be transformed to a dictionary comprehension like this:
dic2 = v: k for k, values in dic.items() for v in values
You can remember that the order of for
clauses in the comprehension is the same as the order of corresponding nested for
loops.
Potential pitfalls
You should be aware that this transformation from a dictionary of lists to a reverse dictionary only works if all items in the original lists are unique. Counterexample:
>>> dic = 0: [1, 2], 1: [2, 3]
>>> v: k for k, values in dic.items() for v in values
1: 0, 2: 1, 3: 1 # missing 2: 0
To correct this, the output dictionary should have the same format as the input, namely mapping each of the items in the input lists to a list of corresponding keys.
If the input represents a directed graph (mapping nodes to lists of neighbours), this corresponds to computing the transposed or reversed graph. It can be done by using a collections.defaultdict
. I don't see an easy way to write it as a comprehension in this case.
from collections import defaultdict
graph = 0: [1, 2], 1: [2, 3]
transposed_graph = defaultdict(list)
for node, neighbours in graph.items():
for neighbour in neighbours:
transposed_graph[neighbour].append(node)
# 1: [0], 2: [0, 1], 3: [1]
$endgroup$
add a comment |
$begingroup$
There's really not much to say about this code, it is straightforward.
Style
These are only nitpicks.
- Generic dictionary keys are typically named
k
instead ofi
orj
, but in a specific application a more descriptive name would be even better. - Collections should be named by their purpose in the application, not their type.
- By convention, assignments and other binary operators should be surrounded by spaces:
a = b
, nota=b
. See PEP 8 for reference, if you're not already aware of it. Following this style guide makes your code easier to read for others.
Code improvements
When iterating over the keys and values of a dictionary at the same time, you can use
for k, v in dic.items():
# ... use k, v ...
instead of
for k in dic:
v = dic[k]
# ...
The nested loop can be transformed to a dictionary comprehension like this:
dic2 = v: k for k, values in dic.items() for v in values
You can remember that the order of for
clauses in the comprehension is the same as the order of corresponding nested for
loops.
Potential pitfalls
You should be aware that this transformation from a dictionary of lists to a reverse dictionary only works if all items in the original lists are unique. Counterexample:
>>> dic = 0: [1, 2], 1: [2, 3]
>>> v: k for k, values in dic.items() for v in values
1: 0, 2: 1, 3: 1 # missing 2: 0
To correct this, the output dictionary should have the same format as the input, namely mapping each of the items in the input lists to a list of corresponding keys.
If the input represents a directed graph (mapping nodes to lists of neighbours), this corresponds to computing the transposed or reversed graph. It can be done by using a collections.defaultdict
. I don't see an easy way to write it as a comprehension in this case.
from collections import defaultdict
graph = 0: [1, 2], 1: [2, 3]
transposed_graph = defaultdict(list)
for node, neighbours in graph.items():
for neighbour in neighbours:
transposed_graph[neighbour].append(node)
# 1: [0], 2: [0, 1], 3: [1]
$endgroup$
There's really not much to say about this code, it is straightforward.
Style
These are only nitpicks.
- Generic dictionary keys are typically named
k
instead ofi
orj
, but in a specific application a more descriptive name would be even better. - Collections should be named by their purpose in the application, not their type.
- By convention, assignments and other binary operators should be surrounded by spaces:
a = b
, nota=b
. See PEP 8 for reference, if you're not already aware of it. Following this style guide makes your code easier to read for others.
Code improvements
When iterating over the keys and values of a dictionary at the same time, you can use
for k, v in dic.items():
# ... use k, v ...
instead of
for k in dic:
v = dic[k]
# ...
The nested loop can be transformed to a dictionary comprehension like this:
dic2 = v: k for k, values in dic.items() for v in values
You can remember that the order of for
clauses in the comprehension is the same as the order of corresponding nested for
loops.
Potential pitfalls
You should be aware that this transformation from a dictionary of lists to a reverse dictionary only works if all items in the original lists are unique. Counterexample:
>>> dic = 0: [1, 2], 1: [2, 3]
>>> v: k for k, values in dic.items() for v in values
1: 0, 2: 1, 3: 1 # missing 2: 0
To correct this, the output dictionary should have the same format as the input, namely mapping each of the items in the input lists to a list of corresponding keys.
If the input represents a directed graph (mapping nodes to lists of neighbours), this corresponds to computing the transposed or reversed graph. It can be done by using a collections.defaultdict
. I don't see an easy way to write it as a comprehension in this case.
from collections import defaultdict
graph = 0: [1, 2], 1: [2, 3]
transposed_graph = defaultdict(list)
for node, neighbours in graph.items():
for neighbour in neighbours:
transposed_graph[neighbour].append(node)
# 1: [0], 2: [0, 1], 3: [1]
answered 4 hours ago
mkrieger1mkrieger1
1,4131824
1,4131824
add a comment |
add a comment |
Juan C is a new contributor. Be nice, and check out our Code of Conduct.
Juan C is a new contributor. Be nice, and check out our Code of Conduct.
Juan C is a new contributor. Be nice, and check out our Code of Conduct.
Juan C is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- 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.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
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%2fcodereview.stackexchange.com%2fquestions%2f216814%2freverse-dictionary-where-values-are-lists%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');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
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');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
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');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
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