Python adding to dictionary only by key
Let's say i have a city (value) and people (key).
1 city can have many people.
(For example.):
Code:
cities = {'Berlin':{'Dan', 'john'},'Tokyo':{'John'}}
city_dict = {}
people = {}
for city in cities:
?
i want to construct a dictionary in python which insert only if a match between keys occurring.
(For example the desired result.):
{'dan' : {'dan':'berlin','dan':'colorado'},'john' : {'john':'berlin','john':'Tokyo'}}
Thanks.
python dictionary
add a comment |
Let's say i have a city (value) and people (key).
1 city can have many people.
(For example.):
Code:
cities = {'Berlin':{'Dan', 'john'},'Tokyo':{'John'}}
city_dict = {}
people = {}
for city in cities:
?
i want to construct a dictionary in python which insert only if a match between keys occurring.
(For example the desired result.):
{'dan' : {'dan':'berlin','dan':'colorado'},'john' : {'john':'berlin','john':'Tokyo'}}
Thanks.
python dictionary
1
What about{'dan' : {'berlin', 'colorado'},'john' : {'berlin', 'Tokyo'}}
? Why do you need the names again and again anyway?
– Ayxan
Dec 31 '18 at 11:38
add a comment |
Let's say i have a city (value) and people (key).
1 city can have many people.
(For example.):
Code:
cities = {'Berlin':{'Dan', 'john'},'Tokyo':{'John'}}
city_dict = {}
people = {}
for city in cities:
?
i want to construct a dictionary in python which insert only if a match between keys occurring.
(For example the desired result.):
{'dan' : {'dan':'berlin','dan':'colorado'},'john' : {'john':'berlin','john':'Tokyo'}}
Thanks.
python dictionary
Let's say i have a city (value) and people (key).
1 city can have many people.
(For example.):
Code:
cities = {'Berlin':{'Dan', 'john'},'Tokyo':{'John'}}
city_dict = {}
people = {}
for city in cities:
?
i want to construct a dictionary in python which insert only if a match between keys occurring.
(For example the desired result.):
{'dan' : {'dan':'berlin','dan':'colorado'},'john' : {'john':'berlin','john':'Tokyo'}}
Thanks.
python dictionary
python dictionary
edited Dec 31 '18 at 11:32
DeepSpace
38.5k44470
38.5k44470
asked Dec 31 '18 at 11:31
MoZZMoZZ
396
396
1
What about{'dan' : {'berlin', 'colorado'},'john' : {'berlin', 'Tokyo'}}
? Why do you need the names again and again anyway?
– Ayxan
Dec 31 '18 at 11:38
add a comment |
1
What about{'dan' : {'berlin', 'colorado'},'john' : {'berlin', 'Tokyo'}}
? Why do you need the names again and again anyway?
– Ayxan
Dec 31 '18 at 11:38
1
1
What about
{'dan' : {'berlin', 'colorado'},'john' : {'berlin', 'Tokyo'}}
? Why do you need the names again and again anyway?– Ayxan
Dec 31 '18 at 11:38
What about
{'dan' : {'berlin', 'colorado'},'john' : {'berlin', 'Tokyo'}}
? Why do you need the names again and again anyway?– Ayxan
Dec 31 '18 at 11:38
add a comment |
3 Answers
3
active
oldest
votes
The desired result can't be achieved as dictionaries, by definition, can't contain duplicated keys.
You can, however, do the following (which is somehow close to the output you wanted):
from collections import defaultdict
cities = {'Berlin': {'Dan', 'John'}, 'Tokyo': {'John'}}
output = defaultdict(set)
for city, names in cities.items():
for name in names:
output[name].add(city)
print(output)
# defaultdict(<class 'set'>, {'Dan': {'Berlin'}, 'John': {'Berlin', 'Tokyo'}})
add a comment |
Other option, without dependencies and returning list of cities:
cities = {'Berlin':{'Dan', 'John'},'Tokyo':{'John', 'Paul'}, 'Liverpool':{'John', 'Paul', 'George', 'Ringo'}, 'Colorado':{'Ringo'} }
res = {}
for k, v in cities.items():
for e in v:
res.setdefault(e,).append(k)
print(res)
#=> {'Dan': ['Berlin'], 'John': ['Berlin', 'Tokyo', 'Liverpool'], 'Paul': ['Tokyo', 'Liverpool'], 'Ringo': ['Liverpool', 'Colorado'], 'George': ['Liverpool']}
add a comment |
You can't have a dictionary with duplicate keys like @DeepSpace indicated, so for your problem I can suggest you the following alternative.
Use a dictionary with people's name for keys and for value the cities. And so when you want when combine the two for creating a list tuples or so on.
people = {"Dan": ["Berlin","San Francisco"], "Mario": ["Rome"]}
for name, locations in people:
#combine name with single city if needed
for city in locations:
tuple_tmp = (name,city)
#next store it, print it,...
This approach cons are:
- You need to process the values
- If you have city and and want to retrieve all names in this one is very slow operation.
You can maintain another structure with the inverted relation, but it's memory consuming.
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%2f53986957%2fpython-adding-to-dictionary-only-by-key%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
The desired result can't be achieved as dictionaries, by definition, can't contain duplicated keys.
You can, however, do the following (which is somehow close to the output you wanted):
from collections import defaultdict
cities = {'Berlin': {'Dan', 'John'}, 'Tokyo': {'John'}}
output = defaultdict(set)
for city, names in cities.items():
for name in names:
output[name].add(city)
print(output)
# defaultdict(<class 'set'>, {'Dan': {'Berlin'}, 'John': {'Berlin', 'Tokyo'}})
add a comment |
The desired result can't be achieved as dictionaries, by definition, can't contain duplicated keys.
You can, however, do the following (which is somehow close to the output you wanted):
from collections import defaultdict
cities = {'Berlin': {'Dan', 'John'}, 'Tokyo': {'John'}}
output = defaultdict(set)
for city, names in cities.items():
for name in names:
output[name].add(city)
print(output)
# defaultdict(<class 'set'>, {'Dan': {'Berlin'}, 'John': {'Berlin', 'Tokyo'}})
add a comment |
The desired result can't be achieved as dictionaries, by definition, can't contain duplicated keys.
You can, however, do the following (which is somehow close to the output you wanted):
from collections import defaultdict
cities = {'Berlin': {'Dan', 'John'}, 'Tokyo': {'John'}}
output = defaultdict(set)
for city, names in cities.items():
for name in names:
output[name].add(city)
print(output)
# defaultdict(<class 'set'>, {'Dan': {'Berlin'}, 'John': {'Berlin', 'Tokyo'}})
The desired result can't be achieved as dictionaries, by definition, can't contain duplicated keys.
You can, however, do the following (which is somehow close to the output you wanted):
from collections import defaultdict
cities = {'Berlin': {'Dan', 'John'}, 'Tokyo': {'John'}}
output = defaultdict(set)
for city, names in cities.items():
for name in names:
output[name].add(city)
print(output)
# defaultdict(<class 'set'>, {'Dan': {'Berlin'}, 'John': {'Berlin', 'Tokyo'}})
answered Dec 31 '18 at 11:36
DeepSpaceDeepSpace
38.5k44470
38.5k44470
add a comment |
add a comment |
Other option, without dependencies and returning list of cities:
cities = {'Berlin':{'Dan', 'John'},'Tokyo':{'John', 'Paul'}, 'Liverpool':{'John', 'Paul', 'George', 'Ringo'}, 'Colorado':{'Ringo'} }
res = {}
for k, v in cities.items():
for e in v:
res.setdefault(e,).append(k)
print(res)
#=> {'Dan': ['Berlin'], 'John': ['Berlin', 'Tokyo', 'Liverpool'], 'Paul': ['Tokyo', 'Liverpool'], 'Ringo': ['Liverpool', 'Colorado'], 'George': ['Liverpool']}
add a comment |
Other option, without dependencies and returning list of cities:
cities = {'Berlin':{'Dan', 'John'},'Tokyo':{'John', 'Paul'}, 'Liverpool':{'John', 'Paul', 'George', 'Ringo'}, 'Colorado':{'Ringo'} }
res = {}
for k, v in cities.items():
for e in v:
res.setdefault(e,).append(k)
print(res)
#=> {'Dan': ['Berlin'], 'John': ['Berlin', 'Tokyo', 'Liverpool'], 'Paul': ['Tokyo', 'Liverpool'], 'Ringo': ['Liverpool', 'Colorado'], 'George': ['Liverpool']}
add a comment |
Other option, without dependencies and returning list of cities:
cities = {'Berlin':{'Dan', 'John'},'Tokyo':{'John', 'Paul'}, 'Liverpool':{'John', 'Paul', 'George', 'Ringo'}, 'Colorado':{'Ringo'} }
res = {}
for k, v in cities.items():
for e in v:
res.setdefault(e,).append(k)
print(res)
#=> {'Dan': ['Berlin'], 'John': ['Berlin', 'Tokyo', 'Liverpool'], 'Paul': ['Tokyo', 'Liverpool'], 'Ringo': ['Liverpool', 'Colorado'], 'George': ['Liverpool']}
Other option, without dependencies and returning list of cities:
cities = {'Berlin':{'Dan', 'John'},'Tokyo':{'John', 'Paul'}, 'Liverpool':{'John', 'Paul', 'George', 'Ringo'}, 'Colorado':{'Ringo'} }
res = {}
for k, v in cities.items():
for e in v:
res.setdefault(e,).append(k)
print(res)
#=> {'Dan': ['Berlin'], 'John': ['Berlin', 'Tokyo', 'Liverpool'], 'Paul': ['Tokyo', 'Liverpool'], 'Ringo': ['Liverpool', 'Colorado'], 'George': ['Liverpool']}
answered Dec 31 '18 at 11:54
iGianiGian
3,9832623
3,9832623
add a comment |
add a comment |
You can't have a dictionary with duplicate keys like @DeepSpace indicated, so for your problem I can suggest you the following alternative.
Use a dictionary with people's name for keys and for value the cities. And so when you want when combine the two for creating a list tuples or so on.
people = {"Dan": ["Berlin","San Francisco"], "Mario": ["Rome"]}
for name, locations in people:
#combine name with single city if needed
for city in locations:
tuple_tmp = (name,city)
#next store it, print it,...
This approach cons are:
- You need to process the values
- If you have city and and want to retrieve all names in this one is very slow operation.
You can maintain another structure with the inverted relation, but it's memory consuming.
add a comment |
You can't have a dictionary with duplicate keys like @DeepSpace indicated, so for your problem I can suggest you the following alternative.
Use a dictionary with people's name for keys and for value the cities. And so when you want when combine the two for creating a list tuples or so on.
people = {"Dan": ["Berlin","San Francisco"], "Mario": ["Rome"]}
for name, locations in people:
#combine name with single city if needed
for city in locations:
tuple_tmp = (name,city)
#next store it, print it,...
This approach cons are:
- You need to process the values
- If you have city and and want to retrieve all names in this one is very slow operation.
You can maintain another structure with the inverted relation, but it's memory consuming.
add a comment |
You can't have a dictionary with duplicate keys like @DeepSpace indicated, so for your problem I can suggest you the following alternative.
Use a dictionary with people's name for keys and for value the cities. And so when you want when combine the two for creating a list tuples or so on.
people = {"Dan": ["Berlin","San Francisco"], "Mario": ["Rome"]}
for name, locations in people:
#combine name with single city if needed
for city in locations:
tuple_tmp = (name,city)
#next store it, print it,...
This approach cons are:
- You need to process the values
- If you have city and and want to retrieve all names in this one is very slow operation.
You can maintain another structure with the inverted relation, but it's memory consuming.
You can't have a dictionary with duplicate keys like @DeepSpace indicated, so for your problem I can suggest you the following alternative.
Use a dictionary with people's name for keys and for value the cities. And so when you want when combine the two for creating a list tuples or so on.
people = {"Dan": ["Berlin","San Francisco"], "Mario": ["Rome"]}
for name, locations in people:
#combine name with single city if needed
for city in locations:
tuple_tmp = (name,city)
#next store it, print it,...
This approach cons are:
- You need to process the values
- If you have city and and want to retrieve all names in this one is very slow operation.
You can maintain another structure with the inverted relation, but it's memory consuming.
edited Dec 31 '18 at 12:48
answered Dec 31 '18 at 11:50
IulianIulian
14018
14018
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%2f53986957%2fpython-adding-to-dictionary-only-by-key%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 about
{'dan' : {'berlin', 'colorado'},'john' : {'berlin', 'Tokyo'}}
? Why do you need the names again and again anyway?– Ayxan
Dec 31 '18 at 11:38