Home > Mobile >  How to combine list and dict together row by row
How to combine list and dict together row by row

Time:11-29

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.

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
}

CodePudding user response:

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.

  • Related