How to Combine Two Lists into a Dictionary in Python

How do I combine two lists into a dictionary in Python?

dict(zip([1,2,3,4], [a,b,c,d]))

If the lists are big you should use itertools.izip.

If you have more keys than values, and you want to fill in values for the extra keys, you can use itertools.izip_longest.

Here, a, b, c, and d are variables -- it will work fine (so long as they are defined), but you probably meant ['a','b','c','d'] if you want them as strings.

zip takes the first item from each iterable and makes a tuple, then the second item from each, etc. etc.

dict can take an iterable of iterables, where each inner iterable has two items -- it then uses the first as the key and the second as the value for each item.

Merge two lists into one dict that may contain several values for each key

Python does not have multidicts, so you have two options:

  1. use multidicts from an existing library e.g. werkzeug's MultiDict, when initialised with lists of pairs, will associate multiple values to keys which are present multiple times (unlike dict which will only keep the last value)

    system_data_dict = werkzeug.datastructures.MultiDict(zip(system, instrument))
    system_data_dict.getlist('System A') # => ['Instrument 1', 'Instrument 2']
  2. alternatively, do that by hand by using a regular loop, even if it's feasible using a comprehension (which I'm not sure about) it's going to look dreadful: use a defaultdict or the dict.setdefault method to define a dict mapping keys to lists and append values every time

    system_data_dict = {}
    for k, v in zip(system, instrument):
    system_data_dict.setdefault(k, []).append(v)
    system_data_dict['System A'] # => ['Instrument 1', 'Instrument 2']

Combining two lists into a dictionary in python

 >>> listA = [1, 2, 3, 4, 5]
>>> listB = ["red", "blue", "orange", "black", "grey"]
>>> dict(zip(listA, listB))
{1: 'red', 2: 'blue', 3: 'orange', 4: 'black', 5: 'grey'}

How to combine two lists into dictionary in order?

Try this, I guess this will be your answer.

from collections import OrderedDict

d = OrderedDict(zip(data_ids, tag_ids))
for i, j in d.items():
print(i)
print(j)

Outputs:

22630876
WATCH - Stokes faces unpredictable balls
22626950
'Bad position, but we're not out of it' - de Villiers
22624826
Who is Sandeep Lamichhane?
22626159
WATCH - All the action from the Super Over
22616496
WATCH - Sammy's four-ball blitz
22601480
Shubman Gill's red-hot run streak
22611197
Should bowlers start wearing helmets?
22600498
Keshav Maharaj could be key - Graeme Smith
22605808
WATCH - Kevin Pietersen's match-winning 48
22602601
'It was emotional walking off the pitch' - Stokes
22602543
WATCH - India's gains from the South Africa tour
22594071
WATCH - Best of Kohli in South Africa
22595982
The Ashwin-Gibbs exchange: funny, or not?
22593725
Mayank Agarwal's incredible run of domestic form
22591441
'SA can't afford spicy pitches against Australia'
22553315
Ice Cricket: Legends play T20 in the Alps
22584758
Dhoni, Kohli and quirky on-field chatter

How to merge two lists into dictionary without using nested for loop

You can use a defaultdict:

from collections import defaultdict
d = defaultdict(list)
list_a = [0, 0, 0, 1, 1, 1, 1, 1, 9999]
list_b = [24, 53, 88, 32, 45, 24, 88, 53, 1]
for a, b in zip(list_a, list_b):
d[a].append(b)

print(dict(d))

Output:

{0: [24, 53, 88], 1: [32, 45, 24, 88, 53], 9999: [1]}

merge two lists into dictionary

You can try this:

l1 = [1, 3, 6, 0, 1, 1]
l2 = ['foo1', 'foo2', 'foo1', 'foo2', 'foo2', 'bar1']

data = [{k: v} for k, v in zip(l2, l1)]

print(data)

Output:

[{'foo1': 1}, {'foo2': 3}, {'foo1': 6}, {'foo2': 0}, {'foo2': 1}, {'bar1': 1}]

I wouldn't consider this an ideal data structure though, unless you have a lot more data in the individual dictionaries.

How can I make a dictionary (dict) from separate lists of keys and values?

Like this:

keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) # {'a': 1, 'b': 2, 'c': 3}

Voila :-) The pairwise dict constructor and zip function are awesomely useful.



Related Topics



Leave a reply



Submit