converting two lists to dictionary code example

Example 1: convert two lists to a single dictionary python

#initialize lists

key_list = ['red', 'green', 'blue']
value_list = [1, 2, 3]

#convert lists

my_dict = {} 
for key in key_list: 
    for value in value_list: 
        my_dict[key] = value 
        value_list.remove(value) 
        break  
print(my_dict)

Example 2: merge two list of dictionaries python with string

import pandas as pd

l1 = [{'id': 9, 'av': 4}, {'id': 10, 'av': 0}, {'id': 8, 'av': 0}]
l2 = [{'id': 9, 'nv': 45}, {'id': 10, 'nv': 0}, {'id': 8, 'nv': 30}]

df1 = pd.DataFrame(l1).set_index('id')
df2 = pd.DataFrame(l2).set_index('id')
df = df1.merge(df2, left_index=True, right_index=True)
df.T.to_dict()
# {9: {'av': 4, 'nv': 45}, 10: {'av': 0, 'nv': 0}, 8: {'av': 0, 'nv': 30}}