Write a Python program to split a given dictionary of lists into list of dictionaries.

 Original dictionary of lists:
{'Science': [88, 89, 62, 95], 'Language': [77, 78, 84, 80]}


Split said dictionary of lists into list of dictionaries:
[{'Science': 88, 'Language': 77},{'Science': 89, 'Language': 78},
{'Science': 62, 'Language': 84}, {'Science': 95, 'Language': 80}]

Program:-

l1=[88,89,62,95]
l2=[77,78,84,80]
l3=[]

tempdict={'Science':0,'Language':0} #temporary dictionary
t2={} #temporary dictionary
dict2={'Science':l1,'Language':l2} #Dictionary given
print(dict2)

a=dict2.get('Science')
b=dict2.get('Language')
n=len(l1)

for i in range(0,n):
    tempdict.update({'Science':a[i]})
    tempdict.update({'Language':b[i]}) #Logic used
    t2=tempdict.copy()
    l3.append(t2)

print(l3)

Output:-


Program Explanation:-

Firstly, there are two list l1 and l2, l3 list is for final result. Thereby, declare two temporary dictionaries which are tempdict, t2 whereas dict2 is the dictionary in which Science key contains l1 list values and Language key contains l2 list values.

a=dict2.get('Science') stores all values of Science key inside a list.
b=dict2.get('Language') stores all values of Language key inside b list.

Length is stored inside n variable.

Afterwards, for loop is used within a range 0 to n:
Here, update tempdict (dictionary) with keys Science and Language and assign values from a and b list respectively. Copy the dictionary tempdict into t2, thereby append l3 list which is currently empty.
Hence, l3 is printed.

Comments