Use else in dict comprehension
From two dictionaries:
d1 = {a:a for a in 'abcdefg'}
d2 = {n:n for n in range(10)}
How can I create a third one like:
new_dict = {k:d1[k] if k in d1.keys() else k:d2[k] for k in 'abc123' }
It's throwing a syntax Error, but with list comprehension seems to be fine:
[a if a else 2 for a in [0,1,0,3]]
out: [2, 1, 2, 3]
Moreover, why this works:
{k:d1[k] for k in 'abc123' if k in d1.keys() }
and this doesn't:
{k:d1[k] if k in d1.keys() for k in 'abc123' }
python dictionary list-comprehension
add a comment |
From two dictionaries:
d1 = {a:a for a in 'abcdefg'}
d2 = {n:n for n in range(10)}
How can I create a third one like:
new_dict = {k:d1[k] if k in d1.keys() else k:d2[k] for k in 'abc123' }
It's throwing a syntax Error, but with list comprehension seems to be fine:
[a if a else 2 for a in [0,1,0,3]]
out: [2, 1, 2, 3]
Moreover, why this works:
{k:d1[k] for k in 'abc123' if k in d1.keys() }
and this doesn't:
{k:d1[k] if k in d1.keys() for k in 'abc123' }
python dictionary list-comprehension
1
What is an expected output fornew_dict? Is fairly unclear what you asking for. You are currently using ternary operator for pairsk:vwhich is illegal, but you easily may use it forkand forvindividually.
– Łukasz Rogalski
Sep 5 '16 at 16:09
@ŁukaszRogalski I want to create a new dict with the keys 'abc123' , the values for those keys are in the two other dicts I already have.
– Luis Ramon Ramirez Rodriguez
Sep 5 '16 at 16:22
add a comment |
From two dictionaries:
d1 = {a:a for a in 'abcdefg'}
d2 = {n:n for n in range(10)}
How can I create a third one like:
new_dict = {k:d1[k] if k in d1.keys() else k:d2[k] for k in 'abc123' }
It's throwing a syntax Error, but with list comprehension seems to be fine:
[a if a else 2 for a in [0,1,0,3]]
out: [2, 1, 2, 3]
Moreover, why this works:
{k:d1[k] for k in 'abc123' if k in d1.keys() }
and this doesn't:
{k:d1[k] if k in d1.keys() for k in 'abc123' }
python dictionary list-comprehension
From two dictionaries:
d1 = {a:a for a in 'abcdefg'}
d2 = {n:n for n in range(10)}
How can I create a third one like:
new_dict = {k:d1[k] if k in d1.keys() else k:d2[k] for k in 'abc123' }
It's throwing a syntax Error, but with list comprehension seems to be fine:
[a if a else 2 for a in [0,1,0,3]]
out: [2, 1, 2, 3]
Moreover, why this works:
{k:d1[k] for k in 'abc123' if k in d1.keys() }
and this doesn't:
{k:d1[k] if k in d1.keys() for k in 'abc123' }
python dictionary list-comprehension
python dictionary list-comprehension
edited Sep 5 '16 at 16:23
Łukasz Rogalski
14.4k63568
14.4k63568
asked Sep 5 '16 at 16:03
Luis Ramon Ramirez RodriguezLuis Ramon Ramirez Rodriguez
1,38063060
1,38063060
1
What is an expected output fornew_dict? Is fairly unclear what you asking for. You are currently using ternary operator for pairsk:vwhich is illegal, but you easily may use it forkand forvindividually.
– Łukasz Rogalski
Sep 5 '16 at 16:09
@ŁukaszRogalski I want to create a new dict with the keys 'abc123' , the values for those keys are in the two other dicts I already have.
– Luis Ramon Ramirez Rodriguez
Sep 5 '16 at 16:22
add a comment |
1
What is an expected output fornew_dict? Is fairly unclear what you asking for. You are currently using ternary operator for pairsk:vwhich is illegal, but you easily may use it forkand forvindividually.
– Łukasz Rogalski
Sep 5 '16 at 16:09
@ŁukaszRogalski I want to create a new dict with the keys 'abc123' , the values for those keys are in the two other dicts I already have.
– Luis Ramon Ramirez Rodriguez
Sep 5 '16 at 16:22
1
1
What is an expected output for
new_dict? Is fairly unclear what you asking for. You are currently using ternary operator for pairs k:v which is illegal, but you easily may use it for k and for v individually.– Łukasz Rogalski
Sep 5 '16 at 16:09
What is an expected output for
new_dict? Is fairly unclear what you asking for. You are currently using ternary operator for pairs k:v which is illegal, but you easily may use it for k and for v individually.– Łukasz Rogalski
Sep 5 '16 at 16:09
@ŁukaszRogalski I want to create a new dict with the keys 'abc123' , the values for those keys are in the two other dicts I already have.
– Luis Ramon Ramirez Rodriguez
Sep 5 '16 at 16:22
@ŁukaszRogalski I want to create a new dict with the keys 'abc123' , the values for those keys are in the two other dicts I already have.
– Luis Ramon Ramirez Rodriguez
Sep 5 '16 at 16:22
add a comment |
4 Answers
4
active
oldest
votes
You can't use the key-value pair in the else part of ternary conditional like so.
Do this instead:
new_dict = {k: d1[k] if k in d1 else d2[int(k)] for k in 'abc123'}
# ^^<- make value d2[int(k)] on else
print(new_dict)
#{'2': 2, '1': 1, 'b': 'b', 'a': 'a', 'c': 'c', '3': 3}
Note that if k in d1 checks if k is a key in the dictionary d1. No need to call the keys method.
add a comment |
As described, it seems like both your d1 and d2 are artifacts of how you envision solving the problem and aren't essential. How about simply:
>>> dictionary = {k: int(k) if k.isdigit() else k for k in 'abc123'}
>>> dictionary
{'b': 'b', '3': 3, '2': 2, '1': 1, 'a': 'a', 'c': 'c'}
>>>
Or is there more to the problem you're trying to solve?
Yes, actually the keys are words from a list, I don't have an easy way like the method .isdigit() to distinguish those. But they map either on d1 or d2.
– Luis Ramon Ramirez Rodriguez
Sep 5 '16 at 23:09
add a comment |
This is a general answer for dictionary comprehension with "else". I came across this post when I google-searched it, so I hope it helps future googlers.
So lets say I want to create dictionary with a condition on both k and v
A naive way to solve this would look something like this:
{k:v if (condition) else otherk:otherv for k,v in some_dictionary}
This doesn't work, as mentioned before by Moses Koledoye.
However, you can use the following for each part:
{k if condition1 else otherK: v if condition2 else otherV for k,v in some_dictionary}
Note that here, we conditional the key's assignment and the value's assignment.
The most important thing to pay attention to here is the location of the : delimeter between the keys and the values. Hope this helps.
The following is an example for getting a custom dictionary in the following from:
for the english alphabet
from letters A-G would show a positive value for the order of the upper-case letters
from letters J-Z shows a negative value for the order of the small-case letters
This is an example for different keys and values based on a certain condition.
I hope this is explained well enough.
>>> def less_than_H_ascii_val(x):
... return x < ord('H')-ord('A')
...
>>> {chr(k+ord('A')) if less_than_H_ascii_val(k) else chr(k+ord('a')):
... k if less_than_H_ascii_val(k) else -k
... for k in range(26)}
{'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3, 'G': 6, 'F': 5, 'i': -8, 'h': -7, 'k': -10, 'j': -9, 'm': -12, 'l': -11, 'o': -14, 'n': -13, 'q': -16, 'p': -15, 's': -18, 'r': -17, 'u': -20, 't': -19, 'w': -22, 'v': -21, 'y': -24, 'x': -23, 'z': -25}
add a comment |
{k:v1 if condition1 else v2 for k in some_list}
Which is equal to:
{k:(v1 if condition1 else v2) for k in some_list}
The latter is more easily understood
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%2f39334201%2fuse-else-in-dict-comprehension%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can't use the key-value pair in the else part of ternary conditional like so.
Do this instead:
new_dict = {k: d1[k] if k in d1 else d2[int(k)] for k in 'abc123'}
# ^^<- make value d2[int(k)] on else
print(new_dict)
#{'2': 2, '1': 1, 'b': 'b', 'a': 'a', 'c': 'c', '3': 3}
Note that if k in d1 checks if k is a key in the dictionary d1. No need to call the keys method.
add a comment |
You can't use the key-value pair in the else part of ternary conditional like so.
Do this instead:
new_dict = {k: d1[k] if k in d1 else d2[int(k)] for k in 'abc123'}
# ^^<- make value d2[int(k)] on else
print(new_dict)
#{'2': 2, '1': 1, 'b': 'b', 'a': 'a', 'c': 'c', '3': 3}
Note that if k in d1 checks if k is a key in the dictionary d1. No need to call the keys method.
add a comment |
You can't use the key-value pair in the else part of ternary conditional like so.
Do this instead:
new_dict = {k: d1[k] if k in d1 else d2[int(k)] for k in 'abc123'}
# ^^<- make value d2[int(k)] on else
print(new_dict)
#{'2': 2, '1': 1, 'b': 'b', 'a': 'a', 'c': 'c', '3': 3}
Note that if k in d1 checks if k is a key in the dictionary d1. No need to call the keys method.
You can't use the key-value pair in the else part of ternary conditional like so.
Do this instead:
new_dict = {k: d1[k] if k in d1 else d2[int(k)] for k in 'abc123'}
# ^^<- make value d2[int(k)] on else
print(new_dict)
#{'2': 2, '1': 1, 'b': 'b', 'a': 'a', 'c': 'c', '3': 3}
Note that if k in d1 checks if k is a key in the dictionary d1. No need to call the keys method.
edited Sep 5 '16 at 16:18
answered Sep 5 '16 at 16:12
Moses KoledoyeMoses Koledoye
61.6k75876
61.6k75876
add a comment |
add a comment |
As described, it seems like both your d1 and d2 are artifacts of how you envision solving the problem and aren't essential. How about simply:
>>> dictionary = {k: int(k) if k.isdigit() else k for k in 'abc123'}
>>> dictionary
{'b': 'b', '3': 3, '2': 2, '1': 1, 'a': 'a', 'c': 'c'}
>>>
Or is there more to the problem you're trying to solve?
Yes, actually the keys are words from a list, I don't have an easy way like the method .isdigit() to distinguish those. But they map either on d1 or d2.
– Luis Ramon Ramirez Rodriguez
Sep 5 '16 at 23:09
add a comment |
As described, it seems like both your d1 and d2 are artifacts of how you envision solving the problem and aren't essential. How about simply:
>>> dictionary = {k: int(k) if k.isdigit() else k for k in 'abc123'}
>>> dictionary
{'b': 'b', '3': 3, '2': 2, '1': 1, 'a': 'a', 'c': 'c'}
>>>
Or is there more to the problem you're trying to solve?
Yes, actually the keys are words from a list, I don't have an easy way like the method .isdigit() to distinguish those. But they map either on d1 or d2.
– Luis Ramon Ramirez Rodriguez
Sep 5 '16 at 23:09
add a comment |
As described, it seems like both your d1 and d2 are artifacts of how you envision solving the problem and aren't essential. How about simply:
>>> dictionary = {k: int(k) if k.isdigit() else k for k in 'abc123'}
>>> dictionary
{'b': 'b', '3': 3, '2': 2, '1': 1, 'a': 'a', 'c': 'c'}
>>>
Or is there more to the problem you're trying to solve?
As described, it seems like both your d1 and d2 are artifacts of how you envision solving the problem and aren't essential. How about simply:
>>> dictionary = {k: int(k) if k.isdigit() else k for k in 'abc123'}
>>> dictionary
{'b': 'b', '3': 3, '2': 2, '1': 1, 'a': 'a', 'c': 'c'}
>>>
Or is there more to the problem you're trying to solve?
answered Sep 5 '16 at 17:35
cdlanecdlane
17.9k21144
17.9k21144
Yes, actually the keys are words from a list, I don't have an easy way like the method .isdigit() to distinguish those. But they map either on d1 or d2.
– Luis Ramon Ramirez Rodriguez
Sep 5 '16 at 23:09
add a comment |
Yes, actually the keys are words from a list, I don't have an easy way like the method .isdigit() to distinguish those. But they map either on d1 or d2.
– Luis Ramon Ramirez Rodriguez
Sep 5 '16 at 23:09
Yes, actually the keys are words from a list, I don't have an easy way like the method .isdigit() to distinguish those. But they map either on d1 or d2.
– Luis Ramon Ramirez Rodriguez
Sep 5 '16 at 23:09
Yes, actually the keys are words from a list, I don't have an easy way like the method .isdigit() to distinguish those. But they map either on d1 or d2.
– Luis Ramon Ramirez Rodriguez
Sep 5 '16 at 23:09
add a comment |
This is a general answer for dictionary comprehension with "else". I came across this post when I google-searched it, so I hope it helps future googlers.
So lets say I want to create dictionary with a condition on both k and v
A naive way to solve this would look something like this:
{k:v if (condition) else otherk:otherv for k,v in some_dictionary}
This doesn't work, as mentioned before by Moses Koledoye.
However, you can use the following for each part:
{k if condition1 else otherK: v if condition2 else otherV for k,v in some_dictionary}
Note that here, we conditional the key's assignment and the value's assignment.
The most important thing to pay attention to here is the location of the : delimeter between the keys and the values. Hope this helps.
The following is an example for getting a custom dictionary in the following from:
for the english alphabet
from letters A-G would show a positive value for the order of the upper-case letters
from letters J-Z shows a negative value for the order of the small-case letters
This is an example for different keys and values based on a certain condition.
I hope this is explained well enough.
>>> def less_than_H_ascii_val(x):
... return x < ord('H')-ord('A')
...
>>> {chr(k+ord('A')) if less_than_H_ascii_val(k) else chr(k+ord('a')):
... k if less_than_H_ascii_val(k) else -k
... for k in range(26)}
{'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3, 'G': 6, 'F': 5, 'i': -8, 'h': -7, 'k': -10, 'j': -9, 'm': -12, 'l': -11, 'o': -14, 'n': -13, 'q': -16, 'p': -15, 's': -18, 'r': -17, 'u': -20, 't': -19, 'w': -22, 'v': -21, 'y': -24, 'x': -23, 'z': -25}
add a comment |
This is a general answer for dictionary comprehension with "else". I came across this post when I google-searched it, so I hope it helps future googlers.
So lets say I want to create dictionary with a condition on both k and v
A naive way to solve this would look something like this:
{k:v if (condition) else otherk:otherv for k,v in some_dictionary}
This doesn't work, as mentioned before by Moses Koledoye.
However, you can use the following for each part:
{k if condition1 else otherK: v if condition2 else otherV for k,v in some_dictionary}
Note that here, we conditional the key's assignment and the value's assignment.
The most important thing to pay attention to here is the location of the : delimeter between the keys and the values. Hope this helps.
The following is an example for getting a custom dictionary in the following from:
for the english alphabet
from letters A-G would show a positive value for the order of the upper-case letters
from letters J-Z shows a negative value for the order of the small-case letters
This is an example for different keys and values based on a certain condition.
I hope this is explained well enough.
>>> def less_than_H_ascii_val(x):
... return x < ord('H')-ord('A')
...
>>> {chr(k+ord('A')) if less_than_H_ascii_val(k) else chr(k+ord('a')):
... k if less_than_H_ascii_val(k) else -k
... for k in range(26)}
{'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3, 'G': 6, 'F': 5, 'i': -8, 'h': -7, 'k': -10, 'j': -9, 'm': -12, 'l': -11, 'o': -14, 'n': -13, 'q': -16, 'p': -15, 's': -18, 'r': -17, 'u': -20, 't': -19, 'w': -22, 'v': -21, 'y': -24, 'x': -23, 'z': -25}
add a comment |
This is a general answer for dictionary comprehension with "else". I came across this post when I google-searched it, so I hope it helps future googlers.
So lets say I want to create dictionary with a condition on both k and v
A naive way to solve this would look something like this:
{k:v if (condition) else otherk:otherv for k,v in some_dictionary}
This doesn't work, as mentioned before by Moses Koledoye.
However, you can use the following for each part:
{k if condition1 else otherK: v if condition2 else otherV for k,v in some_dictionary}
Note that here, we conditional the key's assignment and the value's assignment.
The most important thing to pay attention to here is the location of the : delimeter between the keys and the values. Hope this helps.
The following is an example for getting a custom dictionary in the following from:
for the english alphabet
from letters A-G would show a positive value for the order of the upper-case letters
from letters J-Z shows a negative value for the order of the small-case letters
This is an example for different keys and values based on a certain condition.
I hope this is explained well enough.
>>> def less_than_H_ascii_val(x):
... return x < ord('H')-ord('A')
...
>>> {chr(k+ord('A')) if less_than_H_ascii_val(k) else chr(k+ord('a')):
... k if less_than_H_ascii_val(k) else -k
... for k in range(26)}
{'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3, 'G': 6, 'F': 5, 'i': -8, 'h': -7, 'k': -10, 'j': -9, 'm': -12, 'l': -11, 'o': -14, 'n': -13, 'q': -16, 'p': -15, 's': -18, 'r': -17, 'u': -20, 't': -19, 'w': -22, 'v': -21, 'y': -24, 'x': -23, 'z': -25}
This is a general answer for dictionary comprehension with "else". I came across this post when I google-searched it, so I hope it helps future googlers.
So lets say I want to create dictionary with a condition on both k and v
A naive way to solve this would look something like this:
{k:v if (condition) else otherk:otherv for k,v in some_dictionary}
This doesn't work, as mentioned before by Moses Koledoye.
However, you can use the following for each part:
{k if condition1 else otherK: v if condition2 else otherV for k,v in some_dictionary}
Note that here, we conditional the key's assignment and the value's assignment.
The most important thing to pay attention to here is the location of the : delimeter between the keys and the values. Hope this helps.
The following is an example for getting a custom dictionary in the following from:
for the english alphabet
from letters A-G would show a positive value for the order of the upper-case letters
from letters J-Z shows a negative value for the order of the small-case letters
This is an example for different keys and values based on a certain condition.
I hope this is explained well enough.
>>> def less_than_H_ascii_val(x):
... return x < ord('H')-ord('A')
...
>>> {chr(k+ord('A')) if less_than_H_ascii_val(k) else chr(k+ord('a')):
... k if less_than_H_ascii_val(k) else -k
... for k in range(26)}
{'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3, 'G': 6, 'F': 5, 'i': -8, 'h': -7, 'k': -10, 'j': -9, 'm': -12, 'l': -11, 'o': -14, 'n': -13, 'q': -16, 'p': -15, 's': -18, 'r': -17, 'u': -20, 't': -19, 'w': -22, 'v': -21, 'y': -24, 'x': -23, 'z': -25}
answered Jul 3 '17 at 13:25
Sir DonnieSir Donnie
836
836
add a comment |
add a comment |
{k:v1 if condition1 else v2 for k in some_list}
Which is equal to:
{k:(v1 if condition1 else v2) for k in some_list}
The latter is more easily understood
add a comment |
{k:v1 if condition1 else v2 for k in some_list}
Which is equal to:
{k:(v1 if condition1 else v2) for k in some_list}
The latter is more easily understood
add a comment |
{k:v1 if condition1 else v2 for k in some_list}
Which is equal to:
{k:(v1 if condition1 else v2) for k in some_list}
The latter is more easily understood
{k:v1 if condition1 else v2 for k in some_list}
Which is equal to:
{k:(v1 if condition1 else v2) for k in some_list}
The latter is more easily understood
edited Nov 19 '18 at 6:48
Rodgort
1236
1236
answered Nov 19 '18 at 6:21
siaosingsiaosing
30124
30124
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%2f39334201%2fuse-else-in-dict-comprehension%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
What is an expected output for
new_dict? Is fairly unclear what you asking for. You are currently using ternary operator for pairsk:vwhich is illegal, but you easily may use it forkand forvindividually.– Łukasz Rogalski
Sep 5 '16 at 16:09
@ŁukaszRogalski I want to create a new dict with the keys 'abc123' , the values for those keys are in the two other dicts I already have.
– Luis Ramon Ramirez Rodriguez
Sep 5 '16 at 16:22