Use list as key in Dictionary Python

PythonServer Side ProgrammingProgramming

If L1 and L2 are list objects containing keys and respective values, following methods can be used to construct dictionary object.

Zip two lists and convert to dictionary using dict[] function

>>> L1 = ['a','b','c','d'] >>> L2 = [1,2,3,4] >>> d = dict[zip[L1,L2]] >>> d {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Using dictionary comprehension syntax

>>> L1 = ['a','b','c','d'] >>> L2 = [1,2,3,4] >>> d = {k:v for k,v in zip[L1,L2]} >>> d {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Published on 08-Feb-2018 19:11:15

Many careers in tech pay over $100,000 per year. With help from Career Karma, you can find a training program that meets your needs and will set you up for a long-term, well-paid career in tech.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Almost any type of value can be used as a dictionary key in Python. You can even use built-in objects like types and functions. However, there are a couple restrictions that dictionary keys must abide by.

First, a given key can appear in a dictionary only once. Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn’t make sense to map a particular key more than once. If you specify a key a second time during the initial creation of a dictionary, then the second occurrence will override the first.

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable. Values, on the other hand, can be any type and can be used more than once.

00:00 You’ve seen so far that dictionaries are very flexible, kind of an awesome data type to work with. But there are a few restrictions I want to briefly talk about. Keys in a dictionary can only be used once. If it is used more than once, as you saw earlier, it’ll simply replace the value.

00:19 A key must be immutable—that is, unable to be changed. These are things like integers, floats, strings, Booleans, functions. Even tuples can be a key. A dictionary or a list cannot be a key. Values, on the other hand, can literally be anything and they can be used more than once.

00:41 Let’s hop into the console for a couple of examples. You’ve seen so far that you can use values of all sorts in a dictionary. The same goes for keys. You don’t have to simply use strings or integers—you can use floats, Booleans, even tuples as keys.

01:00 If we open up an example dictionary here and let’s give it a couple of keys of those types.

01:13 There’s a Boolean. And let’s try with a tuple here.

01:25 Go ahead and close this dictionary off. And you can see it took those without exception. And even call one of those—no problem! So, remember the restrictions we talked about.

01:41 They can only be used once in a dictionary and keys must also be immutable. So, what happens if we use one of those mutable data types? Like a list as a key?

02:02 And try to assign it? Oops, I have plural examples. So you can look here, and our second exception that we got—unhashable type: 'list'.

Become a Member to join the conversation.

In this article we will discuss different ways to convert a single or multiple lists to dictionary in Python.

Following conversions from list to dictionary will be covered here,

  • Convert a List to Dictionary with same values
  • Convert List items as keys in dictionary with enumerated value
  • Convert two lists to dictionary
  • Convert a list of tuples to dictionary

Convert a List to Dictionary with same values

Suppose we have a list of strings i.e.

# List of strings listOfStr = ["hello", "at" , "test" , "this" , "here" , "now" ]
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

''' Converting a list to dictionary with list elements as keys in dictionary All keys will have same value ''' dictOfWords = { i : 5 for i in listOfStr } 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.

Convert List items as keys in dictionary with enumerated value

Suppose we have a list of strings i.e.

# List of strings listOfStr = ["hello", "at" , "test" , "this" , "here" , "now" ] Let’s create a dictionary from this list with list elements as keys and values as integers from 0 to n-1 [n is size of list] i.e.

''' Converting a list to dictionary with list elements as values in dictionary and keys are enumerated index starting from 0 i.e. index position of element in list ''' dictOfWords = { i : listOfStr[i] for i in range[0, len[listOfStr] ] } Dictionary contents will be,0 :: hello 1 :: at 2 :: test 3 :: this 4 :: here 5 :: now

Convert two lists to a dictionary

Suppose we have two lists i.e.

# List of strings listOfStr = ["hello", "at" , "test" , "this" , "here" , "now" ] # List of ints listOfInt = [56, 23, 43, 97, 43, 102] Let’s create a dictionary with elements of listOfStr as keys and elements of listOfInt as values using zip[] i.e

# Create a zip object from two lists zipbObj = zip[listOfStr, listOfInt] # Create a dictionary from zip object dictOfWords = dict[zipbObj] Zip[] accepts a number of iterable objects and returns a list of tuples. Each entry in tuple contains an element from each iterable object.

We have passed two lists objects in zip[] , so it will return a list of tuples, where each tuple contains an entry from both the lists. Then we created a dictionary object from this list of tuples.

Dictionary contents are,

Dictionary from two Lists hello :: 56 here :: 43 this :: 97 test :: 43 at :: 23 now :: 102

  • If length of keys list is less than list of values then remaining elements in value list will be skipped.

Convert a list of tuples to dictionary

Suppose we have a list of tuples with two columns in each entry i.e.

# List of tuples listofTuples = [["Riti" , 11], ["Aadi" , 12], ["Sam" , 13],["John" , 22],["Lucy" , 90]] We can directly pass this list of tuples to dictionary constructor i.e

# Convert a list of tuple to dictionary studentsDict = dict[listofTuples] Entries in first column will become the key and entries in second column will the values in the new dictionary. Contents of dictionary will be,Dictionary from List of Tuples John :: 22 Lucy :: 90 Riti :: 11 Aadi :: 12 Sam :: 13

Python Dictionary Tutorial - Series:

Complete example is as follows,

''' Display contents of dictionary with each key/value pair in seperate line ''' def displatDict[text, dictOfElements] : print["*************"] print[text] for key , value in dictOfElements.items[]: print[key, " :: ", value] def main[]: # List of strings listOfStr = ["hello", "at" , "test" , "this" , "here" , "now" ] ''' Converting a list to dictionary with list elements as keys in dictionary All keys will have same value ''' dictOfWords = { i : 5 for i in listOfStr } displatDict["Dictionary with same value " , dictOfWords] ''' Converting a list to dictionary with list elements as keys in dictionary using dict.fromkeys[] ''' dictOfWords = dict.fromkeys[listOfStr , 1] displatDict["Dictionary with given default value " , dictOfWords] dictOfWords = dict.fromkeys[listOfStr] displatDict["Dictionary with same default value None " , dictOfWords] ''' Converting a list to dictionary with list elements as values in dictionary and keys are enumerated index starting from 0 i.e. index position of element in list ''' dictOfWords = { i : listOfStr[i] for i in range[0, len[listOfStr] ] } displatDict["Dictionary with enumerated keys" , dictOfWords] ''' Converting multiple lists to dictionary using zip list1 will be used as keys and list2 as values ''' # List of strings listOfStr = ["hello", "at" , "test" , "this" , "here" , "now" ] # List of ints listOfInt = [56, 23, 43, 97, 43, 102] # Create a zip object from two lists zipbObj = zip[listOfStr, listOfInt] # Create a dictionary from zip object dictOfWords = dict[zipbObj] displatDict["Dictionary from two Lists " , dictOfWords] ''' If list of keys is greater than list of values then extra keys will be skipped ''' # List of strings listOfStr = ["hello", "at" , "test" , "this" , "here" , "now" ] # List of ints listOfInt = [56, 23, 43, 97, 43] zipbObj = zip[listOfStr, listOfInt] dictOfWords = dict[zipbObj] displatDict["Dictionary from two Lists " , dictOfWords] ''' Convert a list of tuples to Dictionary ''' # List of tuples listofTuples = [["Riti" , 11], ["Aadi" , 12], ["Sam" , 13],["John" , 22],["Lucy" , 90]] # Convert a list of tuple to dictionary studentsDict = dict[listofTuples] displatDict["Dictionary from List of Tuples" , studentsDict] if __name__ == '__main__': main[]
Output
************* Dictionary with same value now :: 5 here :: 5 test :: 5 at :: 5 this :: 5 hello :: 5 ************* Dictionary with given default value now :: 1 here :: 1 test :: 1 at :: 1 this :: 1 hello :: 1 ************* Dictionary with same default value None now :: None here :: None test :: None at :: None this :: None hello :: None ************* Dictionary with enumerated keys 0 :: hello 1 :: at 2 :: test 3 :: this 4 :: here 5 :: now ************* Dictionary from two Lists now :: 102 here :: 43 test :: 43 at :: 23 this :: 97 hello :: 56 ************* Dictionary from two Lists test :: 43 at :: 23 this :: 97 hello :: 56 here :: 43 ************* Dictionary from List of Tuples John :: 22 Lucy :: 90 Riti :: 11 Aadi :: 12 Sam :: 13
 

Video liên quan

Chủ Đề