Python data mutation with a for loop and list comprehension: How to be more Pythonic
$begingroup$
I would like to transform a dict of one format into a dict of another format.
The raw_input
dict will have the shape:
'key': ['list of strings']
I would like to reformat it into a list of dicts with the following shape:
[
{'key': 'string'},
{'key': 'string'},
...etc for each item in the list of strings
]
My implementation is functional but naive, using a doubly nested for loop:
raw_input = {
'error': ['string 1', 'string2'],
'error2': ['string 3']
}
def return_dict_as_list(raw_input):
mylist =
for foo in raw_input:
for bar in raw_input[item]:
mylist.append( { 'mykey': foo, 'myvalue': bar } )
return mylist
The output is as expected but I can't help but think there's a better way.
I did try a couple of list comprehensions, but the output was not what was desired:
for example this:
elist = [[{'field': item, 'message': msg} for msg in raw[item]] for item in raw]
returns nested lists within a list, which I could unpack but doesn't seem very zen.
here's an online repl with the code:
https://repl.it/repls/UnpleasantBiodegradableSystems
python beginner
$endgroup$
add a comment |
$begingroup$
I would like to transform a dict of one format into a dict of another format.
The raw_input
dict will have the shape:
'key': ['list of strings']
I would like to reformat it into a list of dicts with the following shape:
[
{'key': 'string'},
{'key': 'string'},
...etc for each item in the list of strings
]
My implementation is functional but naive, using a doubly nested for loop:
raw_input = {
'error': ['string 1', 'string2'],
'error2': ['string 3']
}
def return_dict_as_list(raw_input):
mylist =
for foo in raw_input:
for bar in raw_input[item]:
mylist.append( { 'mykey': foo, 'myvalue': bar } )
return mylist
The output is as expected but I can't help but think there's a better way.
I did try a couple of list comprehensions, but the output was not what was desired:
for example this:
elist = [[{'field': item, 'message': msg} for msg in raw[item]] for item in raw]
returns nested lists within a list, which I could unpack but doesn't seem very zen.
here's an online repl with the code:
https://repl.it/repls/UnpleasantBiodegradableSystems
python beginner
$endgroup$
$begingroup$
Shouldfor bar in raw_input[item]:
actually befor bar in raw_input[foo]:
?
$endgroup$
– Graipher
30 mins ago
$begingroup$
Also, you should make the purpose of your code the title of your question, not what you want out of a review. Have a look at How to Ask.
$endgroup$
– Graipher
19 mins ago
add a comment |
$begingroup$
I would like to transform a dict of one format into a dict of another format.
The raw_input
dict will have the shape:
'key': ['list of strings']
I would like to reformat it into a list of dicts with the following shape:
[
{'key': 'string'},
{'key': 'string'},
...etc for each item in the list of strings
]
My implementation is functional but naive, using a doubly nested for loop:
raw_input = {
'error': ['string 1', 'string2'],
'error2': ['string 3']
}
def return_dict_as_list(raw_input):
mylist =
for foo in raw_input:
for bar in raw_input[item]:
mylist.append( { 'mykey': foo, 'myvalue': bar } )
return mylist
The output is as expected but I can't help but think there's a better way.
I did try a couple of list comprehensions, but the output was not what was desired:
for example this:
elist = [[{'field': item, 'message': msg} for msg in raw[item]] for item in raw]
returns nested lists within a list, which I could unpack but doesn't seem very zen.
here's an online repl with the code:
https://repl.it/repls/UnpleasantBiodegradableSystems
python beginner
$endgroup$
I would like to transform a dict of one format into a dict of another format.
The raw_input
dict will have the shape:
'key': ['list of strings']
I would like to reformat it into a list of dicts with the following shape:
[
{'key': 'string'},
{'key': 'string'},
...etc for each item in the list of strings
]
My implementation is functional but naive, using a doubly nested for loop:
raw_input = {
'error': ['string 1', 'string2'],
'error2': ['string 3']
}
def return_dict_as_list(raw_input):
mylist =
for foo in raw_input:
for bar in raw_input[item]:
mylist.append( { 'mykey': foo, 'myvalue': bar } )
return mylist
The output is as expected but I can't help but think there's a better way.
I did try a couple of list comprehensions, but the output was not what was desired:
for example this:
elist = [[{'field': item, 'message': msg} for msg in raw[item]] for item in raw]
returns nested lists within a list, which I could unpack but doesn't seem very zen.
here's an online repl with the code:
https://repl.it/repls/UnpleasantBiodegradableSystems
python beginner
python beginner
asked 41 mins ago
timtim
15015
15015
$begingroup$
Shouldfor bar in raw_input[item]:
actually befor bar in raw_input[foo]:
?
$endgroup$
– Graipher
30 mins ago
$begingroup$
Also, you should make the purpose of your code the title of your question, not what you want out of a review. Have a look at How to Ask.
$endgroup$
– Graipher
19 mins ago
add a comment |
$begingroup$
Shouldfor bar in raw_input[item]:
actually befor bar in raw_input[foo]:
?
$endgroup$
– Graipher
30 mins ago
$begingroup$
Also, you should make the purpose of your code the title of your question, not what you want out of a review. Have a look at How to Ask.
$endgroup$
– Graipher
19 mins ago
$begingroup$
Should
for bar in raw_input[item]:
actually be for bar in raw_input[foo]:
?$endgroup$
– Graipher
30 mins ago
$begingroup$
Should
for bar in raw_input[item]:
actually be for bar in raw_input[foo]:
?$endgroup$
– Graipher
30 mins ago
$begingroup$
Also, you should make the purpose of your code the title of your question, not what you want out of a review. Have a look at How to Ask.
$endgroup$
– Graipher
19 mins ago
$begingroup$
Also, you should make the purpose of your code the title of your question, not what you want out of a review. Have a look at How to Ask.
$endgroup$
– Graipher
19 mins ago
add a comment |
1 Answer
1
active
oldest
votes
$begingroup$
You can at least turn the inner for
loop into a list/generator comprehension and use list.extend
:
def return_dict_as_list(raw_input):
mylist =
for key, values in raw_input.items():
my_list.extend({'mykey': key, 'myvalue': value} for value in values)
return mylist
Or you can turn it into one list comprehension with two for
loops in it (but no nested lists):
def return_dict_as_list(raw_input):
return [{'mykey': key, 'myvalue': value}
for key in raw_input
for value in raw_input[key]]
Another approach is to make it a generator:
def to_list_generator(d):
for key, values in d.items():
for value in values:
yield {'mykey': key, 'myvalue': value}
$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
});
}
});
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%2fcodereview.stackexchange.com%2fquestions%2f212387%2fpython-data-mutation-with-a-for-loop-and-list-comprehension-how-to-be-more-pyth%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$
You can at least turn the inner for
loop into a list/generator comprehension and use list.extend
:
def return_dict_as_list(raw_input):
mylist =
for key, values in raw_input.items():
my_list.extend({'mykey': key, 'myvalue': value} for value in values)
return mylist
Or you can turn it into one list comprehension with two for
loops in it (but no nested lists):
def return_dict_as_list(raw_input):
return [{'mykey': key, 'myvalue': value}
for key in raw_input
for value in raw_input[key]]
Another approach is to make it a generator:
def to_list_generator(d):
for key, values in d.items():
for value in values:
yield {'mykey': key, 'myvalue': value}
$endgroup$
add a comment |
$begingroup$
You can at least turn the inner for
loop into a list/generator comprehension and use list.extend
:
def return_dict_as_list(raw_input):
mylist =
for key, values in raw_input.items():
my_list.extend({'mykey': key, 'myvalue': value} for value in values)
return mylist
Or you can turn it into one list comprehension with two for
loops in it (but no nested lists):
def return_dict_as_list(raw_input):
return [{'mykey': key, 'myvalue': value}
for key in raw_input
for value in raw_input[key]]
Another approach is to make it a generator:
def to_list_generator(d):
for key, values in d.items():
for value in values:
yield {'mykey': key, 'myvalue': value}
$endgroup$
add a comment |
$begingroup$
You can at least turn the inner for
loop into a list/generator comprehension and use list.extend
:
def return_dict_as_list(raw_input):
mylist =
for key, values in raw_input.items():
my_list.extend({'mykey': key, 'myvalue': value} for value in values)
return mylist
Or you can turn it into one list comprehension with two for
loops in it (but no nested lists):
def return_dict_as_list(raw_input):
return [{'mykey': key, 'myvalue': value}
for key in raw_input
for value in raw_input[key]]
Another approach is to make it a generator:
def to_list_generator(d):
for key, values in d.items():
for value in values:
yield {'mykey': key, 'myvalue': value}
$endgroup$
You can at least turn the inner for
loop into a list/generator comprehension and use list.extend
:
def return_dict_as_list(raw_input):
mylist =
for key, values in raw_input.items():
my_list.extend({'mykey': key, 'myvalue': value} for value in values)
return mylist
Or you can turn it into one list comprehension with two for
loops in it (but no nested lists):
def return_dict_as_list(raw_input):
return [{'mykey': key, 'myvalue': value}
for key in raw_input
for value in raw_input[key]]
Another approach is to make it a generator:
def to_list_generator(d):
for key, values in d.items():
for value in values:
yield {'mykey': key, 'myvalue': value}
edited 22 mins ago
answered 27 mins ago
GraipherGraipher
24k53585
24k53585
add a comment |
add a comment |
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');
});
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%2f212387%2fpython-data-mutation-with-a-for-loop-and-list-comprehension-how-to-be-more-pyth%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
$begingroup$
Should
for bar in raw_input[item]:
actually befor bar in raw_input[foo]:
?$endgroup$
– Graipher
30 mins ago
$begingroup$
Also, you should make the purpose of your code the title of your question, not what you want out of a review. Have a look at How to Ask.
$endgroup$
– Graipher
19 mins ago