Merging two lists into dictionary while keeping duplicate data in python

后端 未结 8 1956
北海茫月
北海茫月 2021-01-17 09:09

Hi, I want to merge two lists into one dictionary. Suppose I have two lists such as below

list_one = [\'a\', \'a\', \'c\', \'d\']

list_two = [1,2,3,4]

相关标签:
8条回答
  • 2021-01-17 09:35

    As other answers have pointed out, dictionaries have unique keys, however, it is possible to create a structure to mimic the behavior you are looking for:

    class NewDict:
       def __init__(self, *values):
           self.values = list(zip(*values))
       def __getitem__(self, key):
            return [b for a, b in sorted(self.values, key=lambda x:x[0]) if a == key]
       def __repr__(self):
           return "{}({})".format(self.__class__.__name__, "{"+', '.join("{}:{}".format(*i) for i in sorted(self.values, key=lambda x:x[0]))+"}")
    
    list_one = ['a', 'a', 'c', 'd']
    list_two = [1,2,3,4]
    d = NewDict(list_one, list_two)
    print(d['a'])
    print(d)
    

    Output:

    [1, 2]
    NewDict({a:1, a:2, c:3, d:4})
    
    0 讨论(0)
  • 2021-01-17 09:35

    You have two options :

    either you use tuple :

    list_one = ['a', 'a', 'c', 'd']
    
    list_two = [1,2,3,4]
    
    
    
    print(list(map(lambda x,y:(x,y),list_one,list_two)))
    

    output:

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

    Second option is use this pattern:

    dict_1={}
    
    for key,value in zip(list_one,list_two):
        if key not in dict_1:
            dict_1[key]=[value]
        else:
            dict_1[key].append(value)
    
    print(dict_1)
    

    output:

    {'a': [1, 2], 'd': [4], 'c': [3]}
    
    0 讨论(0)
  • 2021-01-17 09:46

    A defining characteristic of dicts is that each key is unique. Thus, you can't have two 'a' keys. Otherwise, what would my_dict['a'] return?

    0 讨论(0)
  • 2021-01-17 09:46

    Since keys in dictionaries are unique, getting {'a': 1, 'a': 2, 'c': 3, 'd': 4} is impossible here for regular python dictionaries, since the key 'a' can only occur once. You can however have a key mapped to multiple values stored in a list, such as {'a': [1, 2], 'c': [3], 'd': [4]}.

    One option is to create a defaultdict to do this easily for you:

    from collections import defaultdict
    
    list_one = ['a', 'a', 'c', 'd']
    
    list_two = [1, 2, 3, 4]
    
    d = defaultdict(list)
    for key, value in zip(list_one, list_two):
        d[key].append(value)
    
    print(dict(d))
    

    Which outputs:

    {'a': [1, 2], 'c': [3], 'd': [4]}
    
    0 讨论(0)
  • 2021-01-17 09:47

    Dictionary has unique keys. If you need the value of 'a' separately store the zipped data in a list or you can use list in values part of the dict and store the values as: {'a': [1,2],'c': [3], 'd': [4]}

    0 讨论(0)
  • 2021-01-17 09:48

    From the documentation for dictionaries:

    It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

    0 讨论(0)
提交回复
热议问题