Home > database >  how to create a dictionary having different number of values at different keys?
how to create a dictionary having different number of values at different keys?

Time:04-09

Question.1 ) I want to create a dictionary , it consist of 8 keys , some keys has 2 values and some keys have 3 values. how to create this kinda dictionary in python.

i been trying using nested loops , but my logic didn't worked.

Desired output

dict_a = { 1:[0,1], 2:[2,3], 3:[4,5], 4:[6,7], 5:[8,9], 6:[10,11], 7:[12,13,14], 8:[15,16,17] }

Question.2 ) If we successfully create the dict_a then, In the second part, i want to merge the multiple values of dict_a according to the dict_b,shown below.

for example :- In dict_b = { 1:[1,2], 2:[2,3]......} ,Here 1:[1,2] means I want to merge 1st and 2nd 'values' of dict_a dictionary, which will give me [0, 1, 2, 3]. similarly 2:[2,3] will give me [2,3,4,5]

dict_b = { 1:[1,2], 2:[2,3], 3:[3,4], 4:[4,5], 5:[5,6], 6:[6,7], 7:[7,8] }

I actually tried the above method successfully, but for two keys 7thand 8th in dict_a , i want to merge with first two values only, i.e when dict_b goes to it's 7th key 7:[7,8], i want the result to be [12,13,15,16] and not [12,13,14,15,16,17].

but the method i used below will merge all inevitably.


dict_a = { 1:[0,1], 2:[2,3], 3:[4,5], 4:[6,7], 5:[8,9], 6:[10,11], 7:[12,13,14], 8:[15,16,17] }

dict_b = { 1:[1,2], 2:[2,3], 3:[3,4], 4:[4,5], 5:[5,6], 6:[6,7], 7:[7,8] }

a_list = []

for i in dict_b:
    tem = []
    a_list.append(tem)
    for j in dict_b[i]:
        tem.extend(dict_a[j])
    print(tem)        

Desired output-

[0, 1, 2, 3]
[2, 3, 4, 5]
[4, 5, 6, 7]
[6, 7, 8, 9]
[8, 9, 10, 11]
[10, 11, 12, 13]
[12, 13, 15, 16]

CodePudding user response:

If you only want to merge with the first 2 values, use a slice.

Change

tem.extend(dict_a[j])

to

tem.extend(dict_a[j][:2])
  • Related