Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to combine list and dict together row by row

I currently have two data where one is a list and one is a dict. Example:

data_1 = {
    '583015': 7,
    '583016': 0,
    '583017': 0,
    '583018': 22,
    '583019': 74,
    '583020': 56,
    '583021': 108,
    '583022': 56,
    '583023': 72,
    '583024': 45,
}

data_2 = [
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
]

and currently what I have done is that I started to do a

for i in data_1:
   print(i)

but I quickly understood I couldn’t call another for loop for data_2 inside data_1… and im stuck.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My question is how can I make each row for data_1 and data_2 to be combined as the expected result below:

Expected:

combined = {
    '1': 7,
    '2': 0,
    '3': 0,
    '4': 22,
    '5': 74,
    '6': 56,
    '7': 108,
    '8': 56,
    '9': 72,
    '10': 45
}

>Solution :

The following solutoin works for Python 3.7+, since in older versions the order of items in dictionary is not guaranteed!

It’s achievable using the following code. In order to iterate through dictionary values, use data_1.values().

data_3 = {}

for Index, value in enumerate(data_1.values()):
    data_3[data_2[Index]] = value

print(data_3)

To learn more about iterating through a dictionary, this article on realpython is a good source.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading