Replacing items in a list in a dictionary with items from another dictionaryHow to merge two dictionaries in a single expression?How do I check if a list is empty?How do I sort a list of dictionaries by a value of the dictionary?What is the best way to iterate over a dictionary?Finding the index of an item given a list containing it in PythonHow do I sort a dictionary by value?Add new keys to a dictionary?Check if a given key already exists in a dictionaryHow do I list all files of a directory?Iterating over dictionaries using 'for' loops

strToHex ( string to its hex representation as string)

What defenses are there against being summoned by the Gate spell?

Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?

Why not use SQL instead of GraphQL?

Is there really no realistic way for a skeleton monster to move around without magic?

Do I have a twin with permutated remainders?

Type 1 Error & Type 2 Error's pregnancy test analogy: is it legit?

Explain the parameters before and after @ in the treminal

Is it possible to make sharp wind that can cut stuff from afar?

Approximately how much travel time was saved by the opening of the Suez Canal in 1869?

Addon: add submenu

Why has Russell's definition of numbers using equivalence classes been finally abandonned? ( If it has actually been abandonned).

What is the offset in a seaplane's hull?

Suffixes -unt and -ut-

Writing rule which states that two causes for the same superpower is bad writing

How to test if a transaction is standard without spending real money?

A newer friend of my brother's gave him a load of baseball cards that are supposedly extremely valuable. Is this a scam?

Can I make popcorn with any corn?

What do the dots in this tr command do: tr .............A-Z A-ZA-Z <<< "JVPQBOV" (with 13 dots)

"You are your self first supporter", a more proper way to say it

Is the language p and n are natural numbers and there's no prime number in [p,p+n] belongs to NP class?

Is it unprofessional to ask if a job posting on GlassDoor is real?

Why linear maps act like matrix multiplication?

Mains transformer blew up amplifier, incorrect description in wiring instructions?



Replacing items in a list in a dictionary with items from another dictionary


How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I sort a list of dictionaries by a value of the dictionary?What is the best way to iterate over a dictionary?Finding the index of an item given a list containing it in PythonHow do I sort a dictionary by value?Add new keys to a dictionary?Check if a given key already exists in a dictionaryHow do I list all files of a directory?Iterating over dictionaries using 'for' loops






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I have the following dictionaries:



d1 = "00f_5" :[1,2,3], "00f_6": [1,2,3]

d2 = ["marker":"00f_5",1: 'AAA',"marker":"00f_6", 1: 'CCC',"marker":"00f_5", 2:"AAC"]


I would like the following output:



d1 = "00f_5" :["AAA","AAC",3], "00f_6": ["CCC",2,3]


I have tried multiple attempts, but I couldn't get it. Any help would be much appreciated.










share|improve this question



















  • 1





    Please post what you have attempted so far, and where did you encounter problems. [SO]: How to create a Minimal, Complete, and Verifiable example (mcve).

    – CristiFati
    Mar 9 at 3:29


















1















I have the following dictionaries:



d1 = "00f_5" :[1,2,3], "00f_6": [1,2,3]

d2 = ["marker":"00f_5",1: 'AAA',"marker":"00f_6", 1: 'CCC',"marker":"00f_5", 2:"AAC"]


I would like the following output:



d1 = "00f_5" :["AAA","AAC",3], "00f_6": ["CCC",2,3]


I have tried multiple attempts, but I couldn't get it. Any help would be much appreciated.










share|improve this question



















  • 1





    Please post what you have attempted so far, and where did you encounter problems. [SO]: How to create a Minimal, Complete, and Verifiable example (mcve).

    – CristiFati
    Mar 9 at 3:29














1












1








1








I have the following dictionaries:



d1 = "00f_5" :[1,2,3], "00f_6": [1,2,3]

d2 = ["marker":"00f_5",1: 'AAA',"marker":"00f_6", 1: 'CCC',"marker":"00f_5", 2:"AAC"]


I would like the following output:



d1 = "00f_5" :["AAA","AAC",3], "00f_6": ["CCC",2,3]


I have tried multiple attempts, but I couldn't get it. Any help would be much appreciated.










share|improve this question
















I have the following dictionaries:



d1 = "00f_5" :[1,2,3], "00f_6": [1,2,3]

d2 = ["marker":"00f_5",1: 'AAA',"marker":"00f_6", 1: 'CCC',"marker":"00f_5", 2:"AAC"]


I would like the following output:



d1 = "00f_5" :["AAA","AAC",3], "00f_6": ["CCC",2,3]


I have tried multiple attempts, but I couldn't get it. Any help would be much appreciated.







python python-3.x dictionary






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 9 at 3:54







Mandie Driskill

















asked Mar 9 at 3:25









Mandie DriskillMandie Driskill

386




386







  • 1





    Please post what you have attempted so far, and where did you encounter problems. [SO]: How to create a Minimal, Complete, and Verifiable example (mcve).

    – CristiFati
    Mar 9 at 3:29













  • 1





    Please post what you have attempted so far, and where did you encounter problems. [SO]: How to create a Minimal, Complete, and Verifiable example (mcve).

    – CristiFati
    Mar 9 at 3:29








1




1





Please post what you have attempted so far, and where did you encounter problems. [SO]: How to create a Minimal, Complete, and Verifiable example (mcve).

– CristiFati
Mar 9 at 3:29






Please post what you have attempted so far, and where did you encounter problems. [SO]: How to create a Minimal, Complete, and Verifiable example (mcve).

– CristiFati
Mar 9 at 3:29













3 Answers
3






active

oldest

votes


















3














You can build a dict that maps the marker to a sub-dict that maps numeric keys to the 3-letter codes, so that given a marker and a numeric key, you can use dict.get method to get the mapped code if it exists:



d = 
for s in d2:
d.setdefault(s['marker'], ).update(s)
d1 = k: [d[k].get(i, i) for i in l] for k, l in d1.items()


so that given:



d1 = "00f_5" :[1,2,3], "00f_6": [1,2,3]
d2 = ["marker":"00f_5",1: 'AAA',"marker":"00f_6", 1: 'CCC',"marker":"00f_5", 2:"AAC"]


d1 will become:



'00f_5': ['AAA', 'AAC', 3], '00f_6': ['CCC', 2, 3]





share|improve this answer






























    0














    Although I will not give you the full program, you might try to understand and play with the following code:



    d2 = ["marker":"00f_5",1: 'AAA',"marker":"00f_6", 1: 'CCC',"marker":"00f_5", 2:"AAC"]

    for d in d2:
    for key, value in d.items():
    if key == "marker":
    marker = value
    else:
    reference = value
    content = key
    print("Marker: , Reference: , Content: ".format(marker, reference, content))





    share|improve this answer






























      0














      I would not suggest overwriting the first dict. Just make a new one (d3).



      Given



      d1 = "00f_5" :[1,2,3], "00f_6": [1,2,3]

      lst = [
      "marker":"00f_5",1: 'AAA',
      "marker":"00f_6", 1: 'CCC',
      "marker":"00f_5", 2:"AAC"
      ]


      Code



      d3 = 
      for d in lst:
      key = d["marker"]
      value = d1[key]
      for k, v in d.items():
      if not isinstance(k, int): # skip to numeric keys
      continue
      if key not in d3: # fill missing entries
      d3[key] = value
      idx = k - 1
      d3[key][idx] = v # overwrite list item

      d3
      '00f_5': ['AAA', 'AAC', 3], '00f_6': ['CCC', 2, 3]





      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%2f55073696%2freplacing-items-in-a-list-in-a-dictionary-with-items-from-another-dictionary%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














        You can build a dict that maps the marker to a sub-dict that maps numeric keys to the 3-letter codes, so that given a marker and a numeric key, you can use dict.get method to get the mapped code if it exists:



        d = 
        for s in d2:
        d.setdefault(s['marker'], ).update(s)
        d1 = k: [d[k].get(i, i) for i in l] for k, l in d1.items()


        so that given:



        d1 = "00f_5" :[1,2,3], "00f_6": [1,2,3]
        d2 = ["marker":"00f_5",1: 'AAA',"marker":"00f_6", 1: 'CCC',"marker":"00f_5", 2:"AAC"]


        d1 will become:



        '00f_5': ['AAA', 'AAC', 3], '00f_6': ['CCC', 2, 3]





        share|improve this answer



























          3














          You can build a dict that maps the marker to a sub-dict that maps numeric keys to the 3-letter codes, so that given a marker and a numeric key, you can use dict.get method to get the mapped code if it exists:



          d = 
          for s in d2:
          d.setdefault(s['marker'], ).update(s)
          d1 = k: [d[k].get(i, i) for i in l] for k, l in d1.items()


          so that given:



          d1 = "00f_5" :[1,2,3], "00f_6": [1,2,3]
          d2 = ["marker":"00f_5",1: 'AAA',"marker":"00f_6", 1: 'CCC',"marker":"00f_5", 2:"AAC"]


          d1 will become:



          '00f_5': ['AAA', 'AAC', 3], '00f_6': ['CCC', 2, 3]





          share|improve this answer

























            3












            3








            3







            You can build a dict that maps the marker to a sub-dict that maps numeric keys to the 3-letter codes, so that given a marker and a numeric key, you can use dict.get method to get the mapped code if it exists:



            d = 
            for s in d2:
            d.setdefault(s['marker'], ).update(s)
            d1 = k: [d[k].get(i, i) for i in l] for k, l in d1.items()


            so that given:



            d1 = "00f_5" :[1,2,3], "00f_6": [1,2,3]
            d2 = ["marker":"00f_5",1: 'AAA',"marker":"00f_6", 1: 'CCC',"marker":"00f_5", 2:"AAC"]


            d1 will become:



            '00f_5': ['AAA', 'AAC', 3], '00f_6': ['CCC', 2, 3]





            share|improve this answer













            You can build a dict that maps the marker to a sub-dict that maps numeric keys to the 3-letter codes, so that given a marker and a numeric key, you can use dict.get method to get the mapped code if it exists:



            d = 
            for s in d2:
            d.setdefault(s['marker'], ).update(s)
            d1 = k: [d[k].get(i, i) for i in l] for k, l in d1.items()


            so that given:



            d1 = "00f_5" :[1,2,3], "00f_6": [1,2,3]
            d2 = ["marker":"00f_5",1: 'AAA',"marker":"00f_6", 1: 'CCC',"marker":"00f_5", 2:"AAC"]


            d1 will become:



            '00f_5': ['AAA', 'AAC', 3], '00f_6': ['CCC', 2, 3]






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 9 at 3:43









            blhsingblhsing

            42.6k41743




            42.6k41743























                0














                Although I will not give you the full program, you might try to understand and play with the following code:



                d2 = ["marker":"00f_5",1: 'AAA',"marker":"00f_6", 1: 'CCC',"marker":"00f_5", 2:"AAC"]

                for d in d2:
                for key, value in d.items():
                if key == "marker":
                marker = value
                else:
                reference = value
                content = key
                print("Marker: , Reference: , Content: ".format(marker, reference, content))





                share|improve this answer



























                  0














                  Although I will not give you the full program, you might try to understand and play with the following code:



                  d2 = ["marker":"00f_5",1: 'AAA',"marker":"00f_6", 1: 'CCC',"marker":"00f_5", 2:"AAC"]

                  for d in d2:
                  for key, value in d.items():
                  if key == "marker":
                  marker = value
                  else:
                  reference = value
                  content = key
                  print("Marker: , Reference: , Content: ".format(marker, reference, content))





                  share|improve this answer

























                    0












                    0








                    0







                    Although I will not give you the full program, you might try to understand and play with the following code:



                    d2 = ["marker":"00f_5",1: 'AAA',"marker":"00f_6", 1: 'CCC',"marker":"00f_5", 2:"AAC"]

                    for d in d2:
                    for key, value in d.items():
                    if key == "marker":
                    marker = value
                    else:
                    reference = value
                    content = key
                    print("Marker: , Reference: , Content: ".format(marker, reference, content))





                    share|improve this answer













                    Although I will not give you the full program, you might try to understand and play with the following code:



                    d2 = ["marker":"00f_5",1: 'AAA',"marker":"00f_6", 1: 'CCC',"marker":"00f_5", 2:"AAC"]

                    for d in d2:
                    for key, value in d.items():
                    if key == "marker":
                    marker = value
                    else:
                    reference = value
                    content = key
                    print("Marker: , Reference: , Content: ".format(marker, reference, content))






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 9 at 3:37









                    mythenmetzmythenmetz

                    856




                    856





















                        0














                        I would not suggest overwriting the first dict. Just make a new one (d3).



                        Given



                        d1 = "00f_5" :[1,2,3], "00f_6": [1,2,3]

                        lst = [
                        "marker":"00f_5",1: 'AAA',
                        "marker":"00f_6", 1: 'CCC',
                        "marker":"00f_5", 2:"AAC"
                        ]


                        Code



                        d3 = 
                        for d in lst:
                        key = d["marker"]
                        value = d1[key]
                        for k, v in d.items():
                        if not isinstance(k, int): # skip to numeric keys
                        continue
                        if key not in d3: # fill missing entries
                        d3[key] = value
                        idx = k - 1
                        d3[key][idx] = v # overwrite list item

                        d3
                        '00f_5': ['AAA', 'AAC', 3], '00f_6': ['CCC', 2, 3]





                        share|improve this answer



























                          0














                          I would not suggest overwriting the first dict. Just make a new one (d3).



                          Given



                          d1 = "00f_5" :[1,2,3], "00f_6": [1,2,3]

                          lst = [
                          "marker":"00f_5",1: 'AAA',
                          "marker":"00f_6", 1: 'CCC',
                          "marker":"00f_5", 2:"AAC"
                          ]


                          Code



                          d3 = 
                          for d in lst:
                          key = d["marker"]
                          value = d1[key]
                          for k, v in d.items():
                          if not isinstance(k, int): # skip to numeric keys
                          continue
                          if key not in d3: # fill missing entries
                          d3[key] = value
                          idx = k - 1
                          d3[key][idx] = v # overwrite list item

                          d3
                          '00f_5': ['AAA', 'AAC', 3], '00f_6': ['CCC', 2, 3]





                          share|improve this answer

























                            0












                            0








                            0







                            I would not suggest overwriting the first dict. Just make a new one (d3).



                            Given



                            d1 = "00f_5" :[1,2,3], "00f_6": [1,2,3]

                            lst = [
                            "marker":"00f_5",1: 'AAA',
                            "marker":"00f_6", 1: 'CCC',
                            "marker":"00f_5", 2:"AAC"
                            ]


                            Code



                            d3 = 
                            for d in lst:
                            key = d["marker"]
                            value = d1[key]
                            for k, v in d.items():
                            if not isinstance(k, int): # skip to numeric keys
                            continue
                            if key not in d3: # fill missing entries
                            d3[key] = value
                            idx = k - 1
                            d3[key][idx] = v # overwrite list item

                            d3
                            '00f_5': ['AAA', 'AAC', 3], '00f_6': ['CCC', 2, 3]





                            share|improve this answer













                            I would not suggest overwriting the first dict. Just make a new one (d3).



                            Given



                            d1 = "00f_5" :[1,2,3], "00f_6": [1,2,3]

                            lst = [
                            "marker":"00f_5",1: 'AAA',
                            "marker":"00f_6", 1: 'CCC',
                            "marker":"00f_5", 2:"AAC"
                            ]


                            Code



                            d3 = 
                            for d in lst:
                            key = d["marker"]
                            value = d1[key]
                            for k, v in d.items():
                            if not isinstance(k, int): # skip to numeric keys
                            continue
                            if key not in d3: # fill missing entries
                            d3[key] = value
                            idx = k - 1
                            d3[key][idx] = v # overwrite list item

                            d3
                            '00f_5': ['AAA', 'AAC', 3], '00f_6': ['CCC', 2, 3]






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 9 at 4:38









                            pylangpylang

                            14.4k24458




                            14.4k24458



























                                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%2f55073696%2freplacing-items-in-a-list-in-a-dictionary-with-items-from-another-dictionary%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

                                Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                                Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                                2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived