user3650827
user3650827

Reputation: 41

python merge list of 1 key and many values dictionaries with the values of a list

I have a dictionary with one key and many values for each key

d={'POU': ['KO', '0.9.8', '0.99', '0.54']
   'TAN': ['LA', '9', '7.5', '0.0']
   'EST': ['RA', '2', '6.5', '10.01']}

and a list of numbers:

x = [**1**, **2**, **3**]

How can I merge the list with the dictionary to have each list's value appended at the end of each line:

d={'POU': ['KO', '0.9.8', '0.99', '0.54', **1**]
   'TAN': ['LA', '9', '7.5', '0.0', **2**]
   'EST': ['RA', '2', '6.5', '10.01', **3**]}

In the same order.

Upvotes: 1

Views: 67

Answers (2)

SpghttCd
SpghttCd

Reputation: 10890

As correctly mentioned by jpp in his comments here, the following solution only works for OrderedDicts or from Python 3.7 on upwards, as otherwise normal dicts do not preserve order:

for i, v in enumerate(d):
    d[v].append(x[i])

d
Out[1]: 
{'EST': ['RA', '2', '6.5', '10.01', '**3**'],
 'POU': ['KO', '0.9.8', '0.99', '0.54', '**1**'],
 'TAN': ['LA', '9', '7.5', '0.0', '**2**']}

Upvotes: 3

Rakesh
Rakesh

Reputation: 82805

Using a simple iteration.

Ex:

d={'POU': ['KO', '0.9.8', '0.99', '0.54'],
   'TAN': ['LA', '9', '7.5', '0.0'],
   'EST': ['RA', '2', '6.5', '10.01']}

x = [1,2, 3]

c = 0
for k,v in d.items():
    v.append(x[c])
    c+=1
print(d)

Output:

{'TAN': ['LA', '9', '7.5', '0.0', 1], 'POU': ['KO', '0.9.8', '0.99', '0.54', 2], 'EST': ['RA', '2', '6.5', '10.01', 3]}

Upvotes: 0

Related Questions