How to create dictionary from list in python

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    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

    def Convert[lst]:

        res_dct = {lst[i]: lst[i + 1] for i in range[0, len[lst], 2]}

        return res_dct

    lst = ['a', 1, 'b', 2, 'c', 3]

    print[Convert[lst]]

    Output

    {'a': 1, 'b': 2, 'c': 3}
    
    

      
    Method #2 : Using zip[] method
    First create an iterator, and initialize it to variable ‘it’. Then use zip method, to zip keys and values together. Finally typecast it to dict type. 
     

    Python3

    def Convert[a]:

        it = iter[a]

        res_dct = dict[zip[it, it]]

        return res_dct

    lst = ['a', 1, 'b', 2, 'c', 3]

    print[Convert[lst]]

    Output

    {'a': 1, 'b': 2, 'c': 3}
    
    


    Till now, we have seen the ways to creating dictionary in multiple ways and different operations on the key and values in dictionary. Now, let’s see different ways of creating a dictionary of list.

    Note that the restriction with keys in Python dictionary is only immutable data types can be used as keys, which means we cannot use a dictionary of list as a key.

    myDict = {[1, 2]: 'Geeks'}

    print[myDict]

    Output:

    TypeError: unhashable type: 'list'

    But the same can be done very wisely with values in dictionary. Let’s see all the different ways we can create a dictionary of Lists.

    Method #1: Using subscript

    myDict = {}

    myDict["key1"] = [1, 2]

    myDict["key2"] = ["Geeks", "For", "Geeks"

    print[myDict]

    Output:

    {'key2': ['Geeks', 'For', 'Geeks'], 'key1': [1, 2]}

     
    Method #2: Adding nested list as value using append[] method.

    Create a new list and we can simply append that list to the value.

    myDict = {}

    myDict["key1"] = [1, 2]

    lst = ['Geeks', 'For', 'Geeks']

    myDict["key1"].append[lst]

    print[myDict]

    Output:

    {'key1': [1, 2, ['Geeks', 'For', 'Geeks']]}

     
    Method #3: Using setdefault[] method

    Iterate the list and keep appending the elements till given range using setdefault[] method.

    myDict = dict[]

    valList = ['1', '2', '3']

    for val in valList:

        for ele in range[int[val], int[val] + 2]: 

            myDict.setdefault[ele, []].append[val]

    print[myDict]

    Output:

    {1: ['1'], 2: ['1', '2'], 3: ['2', '3'], 4: ['3']}

     
    Method #4: Using list comprehension

    d = dict[[val, range[int[val], int[val] + 2]]

                      for val in ['1', '2', '3']]

    print[d]

    Output:

    {'1': [1, 2], '3': [3, 4], '2': [2, 3]}

     
    Method #5: Using defaultdict

    Note that the same thing can also be done with simple dictionary but using defaultdict is more efficient for such cases.

    from collections import defaultdict

    lst = [['Geeks', 1], ['For', 2], ['Geeks', 3]]

    orDict = defaultdict[list]

    for key, val in lst:

        orDict[key].append[val]

    print[orDict]

    Output:

    defaultdict[, {'For': [2], 'Geeks': [1, 3]}]

    Note that there are only two key:value pairs in output dictionary but the input list contains three tuples. The first element[i.e. key] is same for first and third tuple and two keys can never be same.
     
    Method #6: Using Json

    import json

    lst = [['Geeks', 1], ['For', 2], ['Geeks', 3]]

    dict = {}

    hash = json.dumps[lst]

    dict[hash] = "converted"

    print[dict]

    Output:

    {'[["Geeks", 1], ["For", 2], ["Geeks", 3]]': 'converted'}

    How do I convert a list to a dictionary in Python?

    Since python dictionary is unordered, the output can be in any order. 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.

    How do I create a dictionary in multiple lists?

    Use zip[] and dict[] to create a dictionary from two lists Call zip[iter1, iter2] with one list as iter1 and another list as iter2 to create a zip iterator containing pairs of elements from the two lists. Use dict[] to convert this zip iterator to a dictionary of key-value pairs.

    Can a list be a value in a dictionary Python?

    It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.

    Can you create a dictionary with list comprehension?

    We can add a filter to the iterable to a list comprehension to create a dictionary only for particular data based on condition. Filtering means adding values to dictionary-based on conditions.

    Chủ Đề