PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] How do you append two dictionaries such that the result of the value is a list of lists

 July 21, 2022     append, dictionary, dictionary-comprehension, python     No comments   

Issue

I have two dictionaries:

dd = {1: [10, 15], 5: [10, 20, 27], 3: [7]}
dd1 = {1: [1, 4], 5: [2, 5, 6], 3: [3]}

I would like to have the appended dictionary dd look like this:

dd = {1: [[10, 15],[1, 4]], 5: [[10, 20, 27],[2, 5, 6]], 3: [[7],[3]]}

The code I have used to get some what close to this is:

for dictionary in (dd, dd1):
    for key, value in dictionary.items():
        dd[key].append([value])

This doesn't quite work as it appends the list into the list opposed to keeping the two lists separate as a list of lists.


Solution

Assuming d and d1 have the same keys:

d = {1: [10, 15], 5: [10, 20, 27], 3: [7]}
d1 = {1: [1, 4], 5: [2, 5, 6], 3: [3]}

dd = d

for k, v in d1.items():
    dd[k] = [dd[k], v]

print(dd)

Output:

{1: [[10, 15], [1, 4]], 5: [[10, 20, 27], [2, 5, 6]], 3: [[7], [3]]}

Alternative method:

d = {1: [10, 15], 5: [10, 20, 27], 3: [7]}
d1 = {1: [1, 4], 5: [2, 5, 6], 3: [3]}

dd = {}

for key in d.keys():
    dd[key] = [d[key], d1[key]]

print(dd)

Output:

{1: [[10, 15], [1, 4]], 5: [[10, 20, 27], [2, 5, 6]], 3: [[7], [3]]}


Answered By - The Thonnu
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing