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

I have two lists of the same length:

[1,2,3,4] and [a,b,c,d]

I want to create a dictionary where I have {1:a, 2:b, 3:c, 4:d}

What's the best way to do this?

This question is related to python list dictionary

The answer is


>>> dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

If they are not the same size, zip will truncate the longer one.


I don't know about best (simplest? fastest? most readable?), but one way would be:

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

I found myself needing to create a dictionary of three lists (latitude, longitude, and a value), with the following doing the trick:

> lat = [45.3,56.2,23.4,60.4]
> lon = [134.6,128.7,111.9,75.8]
> val = [3,6,2,5]
> dict(zip(zip(lat,lon),val))
{(56.2, 128.7): 6, (60.4, 75.8): 5, (23.4, 111.9): 2, (45.3, 134.6): 3}

or similar to the above examples:

> list1 = [1,2,3,4]
> list2 = [1,2,3,4]
> list3 = ['a','b','c','d']
> dict(zip(zip(list1,list2),list3))
{(3, 3): 'c', (4, 4): 'd', (1, 1): 'a', (2, 2): 'b'}

Note: Dictionaries are "orderless", but if you would like to view it as "sorted", refer to THIS question if you'd like to sort by key, or THIS question if you'd like to sort by value.


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

http://docs.python.org/library/functions.html


If there are duplicate keys in the first list that map to different values in the second list, like a 1-to-many relationship, but you need the values to be combined or added or something instead of updating, you can do this:

i = iter(["a", "a", "b", "c", "b"])
j = iter([1,2,3,4,5])
k = list(zip(i, j))
for (x,y) in k:
    if x in d:
        d[x] = d[x] + y #or whatever your function needs to be to combine them
    else:
        d[x] = y

In that example, d == {'a': 3, 'c': 4, 'b': 8}


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python