Python adding to dictionary only by key












0















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.










share|improve this question




















  • 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
















0















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.










share|improve this question




















  • 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














0












0








0


0






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.










share|improve this question
















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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














  • 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












3 Answers
3






active

oldest

votes


















3














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'}})





share|improve this answer































    2














    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']}





    share|improve this answer































      1














      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.






      share|improve this answer

























        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
        });


        }
        });














        draft saved

        draft discarded


















        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









        3














        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'}})





        share|improve this answer




























          3














          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'}})





          share|improve this answer


























            3












            3








            3







            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'}})





            share|improve this answer













            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'}})






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Dec 31 '18 at 11:36









            DeepSpaceDeepSpace

            38.5k44470




            38.5k44470

























                2














                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']}





                share|improve this answer




























                  2














                  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']}





                  share|improve this answer


























                    2












                    2








                    2







                    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']}





                    share|improve this answer













                    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']}






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Dec 31 '18 at 11:54









                    iGianiGian

                    3,9832623




                    3,9832623























                        1














                        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.






                        share|improve this answer






























                          1














                          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.






                          share|improve this answer




























                            1












                            1








                            1







                            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.






                            share|improve this answer















                            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.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Dec 31 '18 at 12:48

























                            answered Dec 31 '18 at 11:50









                            IulianIulian

                            14018




                            14018






























                                draft saved

                                draft discarded




















































                                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.




                                draft saved


                                draft discarded














                                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





















































                                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







                                Popular posts from this blog

                                Angular Downloading a file using contenturl with Basic Authentication

                                Olmecas

                                Can't read property showImagePicker of undefined in react native iOS