Python | Convert a list to dictionary
Given a list, write a Python program to convert the given list to dictionary such that all the odd elements have the key, and even number elements have the value. Since python dictionary is unordered, the output can be in any order.
Examples:
Input : ['a', 1, 'b', 2, 'c', 3]
Output : {'a': 1, 'b': 2, 'c': 3}
Input : ['Delhi', 71, 'Mumbai', 42]
Output : {'Delhi': 71, 'Mumbai': 42}
Method #1 : dict comprehension
To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.
# Python3 program to Convert a # list to dictionary def Convert(lst): res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)} return res_dct # Driver code lst = ['a', 1, 'b', 2, 'c', 3] print(Convert(lst)) |
{'a': 1, 'b': 2, 'c': 3}
Method #2 : Using zip() method
First create an iterator, and intialise it to variable ‘it’. Then use zip method, to zip keys and values together. Finally typecast it to dict type.
# Python3 program to Convert a # list to dictionary def Convert(a): it = iter(lst) res_dct = dict(zip(it, it)) return res_dct # Driver code lst = ['a', 1, 'b', 2, 'c', 3] print(Convert(lst)) |
{'c': 3, 'b': 2, 'a': 1}
Recommended Posts:
- Python | Convert a list of Tuples into Dictionary
- Python | Convert list of tuple into dictionary
- Python | Convert dictionary to list of tuples
- Python | Convert list of tuples to dictionary value lists
- Python | Convert list of nested dictionary into Pandas dataframe
- Python | Convert flattened dictionary into nested dictionary
- Python | Convert nested dictionary into flattened dictionary
- Python | Convert string dictionary to dictionary
- Python | Convert a set into dictionary
- Python | Convert Tuples to Dictionary
- Python | Convert two lists into a dictionary
- Python | Convert dictionary object into string
- Python | Convert byteString key:value pair of dictionary to String
- Python | Convert key-value pair comma separated string into dictionary
- Python | List value merge in dictionary
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



