Python Lists and DictionariesLists and dictionaries are examples of Python collections. They allow you to store multiple similar values together in one data structure. Show
The list data structure allows you to store data in a specific order. Here is an example of a Python list: takeout_prices = [2.50, 2.75, 4.50, 5.00] Our list called takeout_prices contains four values. Dictionaries, on the other hand, are unordered, and cannot store multiple duplicate values. Here is an example of a Python dictionary: 81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today. Find Your Bootcamp MatchThe average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job. Start your career switch todaytakeout_prices = { 'single_chips': 2.50, 'large_chips': 2.75, 'single_fish': 4.50, 'large_fish': 5.00 } Dictionaries are useful if you want to associate labels with each value. Lists are better if you are storing similar data, such as a list of prices or names, where you cannot label each value. Convert a List to Dictionary with same valuesSuppose we have a list of strings i.e. Now we want to create a dictionary with all elements in this list as keys. For each key value will be same i.e. 5.Let’s see how to do that i.e. Using dictionary comprehension Dictionary contents will be, hello :: 5 here :: 5 this :: 5 test :: 5 at :: 5 now :: 5 Using dict.fromKeys() ''' Converting a list to dictionary with list elements as keys in dictionary using dict.fromkeys() ''' dictOfWords = dict.fromkeys(listOfStr , 1) dict.fromKeys() accepts a list and default value. It returns a dictionary with items in list as keys. All dictionary items will have same value, that was passed in fromkeys(). If no default value was passed in fromKeys() then default value for keys in dictionary will be None. Advertisements How to convert list to dictionary in PythonLists and Dictionaries are two data structure which is used to store the Data. List stores the heterogeneous data type and Dictionary stores data in key-value pair. Here, we are converting the Python list into dictionary. Since list is ordered and dictionary is unordered so output can differ in order. Python list stores the element in the following way. On the other hand, Dictionary is unordered, and stores the unique data. It stores the data in key value pair where each key is associated with it value. Python Dictionary stores the data in following way. In this tutorial, we will learn the conversion Python list to dictionary. Sample Input: Let's understand the following methods. Method - 1 Using Dictionary ComprehensionWe can convert the list into dictionary using the dictionary comprehension. Let's understand the following code. Example - Output: {'James': 'Passed', 'Abhinay': 'Passed', 'Peter': 'Passed', 'Bicky': 'Passed'} Explanation - In the above code, we have created a student list to be converted into the dictionary. Using the dictionary compression, we converted the list in dictionary in a single line. The list elements tuned into key and passed as a value. Let's understand another example. Example - 2 Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100} Explanation: In the above code, we have created square_dict with number-square key/value pair. Method - 2 Using zip() functionThe zip() function is used to zip the two values together. First, we need to create an iterator and initialize to any variable and then typecast to the dict() function. Let's understand the following example. Example - Output: {'x': 1, 'y': 2, 'z': 3} Next TopicHow to declare a global variable in Python ← prev next → How to Convert a Single List to a Dictionary in PythonProvided that a list is symmetric (containing equal potential key-value pairs), you can convert it to a dictionary using the for loop. To do this, place your loop in a dictionary comprehension: m = ["frog", "dog", "Goat", "cat"]d = {m[a]:m[a + 1] for a in range(0, len(m), 2)} print(d) Output: {'frog': 'dog', 'Goat': 'cat'} The code may look complex at first, but it actually isn't. You're only telling Python to pick a pair each time it iterates through your list. Then it should make every item on the left of each pair the key to the one on its right side, which is its value. The integer (2) within the range parenthesis, however, ensures that your code only accepts symmetric lists. To understand its function, change the integer from 2 to 3. Then add an item to the list before running your code.
To achieve this without using the for loop, you can also use the built-in dict and zip functions of Python: a = iter(m) # spin up an iterator on the listresult = dict(zip(a, a)) # Convert the iterated items into key-value pairs print(result) Output: {'frog': 'dog', 'Goat': 'cat'} Unlike the looping method that you used earlier, the dict(zip()) function ignores any item without a pair. For instance, if there are five items in a list, it ignores the fifth one and creates a matching key-value pair with the first four items: m = ["first", "second", "third", "fourth", "fifth_odd"]a = iter(m) result = dict(zip(a, a)) print(result) Output: {'first': 'second', 'third': 'fourth'} How to Convert Two Lists of the Same Length Into a DictionaryAs earlier mentioned, you can convert two lists of equal length into a dictionary, making the items in one of them the keys, while the items in the other list serve as their corresponding values. It isn't as tricky as converting a single list to a dictionary. Here's how to achieve this with the dict(zip()) method: list1 = ["frog", "dog", "Goat", "cat"]list2 = [1, 3, 24, 56] result = dict(zip(list2, list1)) print(result) Output: {1: 'frog', 3: 'dog', 24: 'Goat', 56: 'cat'}
You can also convert two lists into a dictionary using the for loop: list1 = ["frog", "dog", "Goat", "cat", "jog"]list2 = [1, 3, 24, 56 result = {list2[a]:list1[a] for a in range(len(list2))} print(result) Output: {1: 'frog', 3: 'dog', 24: 'Goat', 56: 'cat'} How to Convert list to dictionary in PythonLists and dictionaries are Python collections that allow you to save similar values in one data structure. The list will enable you to save the data in a particular order, whereas dictionaries are unordered and cannot save multiple duplicate values. Converting a list to a dictionary is Python’s standard operation. So let’s see how to do it. Python list to dictionary To convert a Python list to a dictionary, use the list comprehension and make a key-value pair of consecutive elements and then typecast to dictionary type. The return value is converted from a list to a dictionary data type. See the following code example. # app.py def listToDict(lst): op = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)} return op lst = ['m', 1, 'b', 2, 'k', 3] print(listToDict(lst))Output➜ pyt python3 app.py {'m': 1, 'b': 2, 'k': 3} ➜ pytIn the above example, we used the for loop to separate odd and even elements and then used the range() function to form the odd values to key and values to the dictionary. We have used the dictionary comprehension method. So, we get the dictionary converted from the list in the output. 1. Convert List of Primitive Data Types to Dict Using Indices as KeysProblem: Convert a list of primitive data types to a dictionary using the elements’ indices. Example: As an example, take this list: snakes = ['Anaconda', 'Python', 'Cobra', 'Boa', 'Lora' ]
So in the end the dictionary should look like this: d = {0: 'Anaconda', 1: 'Python', 2: 'Cobra', 3: 'Bora', 4: 'Lora'}Solution Idea: Take a dictionary comprehension and use the enumerate function to generate key-value pairs. Now let’s see, how can you implement the logic to achieve this?
Code: And here is the code. # list to convert snakes = ['Anaconda', 'Python', 'Cobra', 'Boa', 'Lora' ] # Short hand constructor of the dict class d = {} for index, value in enumerate(snakes): d[index] = valueAnd that’s all you need, the dictionary d contains just the entries you wanted to have. A more pythonic way to solve the problem is using a dictionary comprehension. This makes the code shorter and in my opinion even simpler to read. Look at this: # list to convert snakes = ['Anaconda', 'Python', 'Cobra', 'Boa', 'Lora' ] # dictionary comprehension d = {index: value for index, value in enumerate(snakes)}Try It Yourself: So once again, Python’s built-in function enumerate cracks the problem, the rest is simple. |