Zip two lists in dictionary but keep duplicates in key

后端 未结 3 707
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 02:55

I have two lists:

alist = [\'key1\',\'key2\',\'key3\',\'key3\',\'key4\',\'key4\',\'key5\']

blist=  [30001,30002,30003,30003,30004,30004,30005]
相关标签:
3条回答
  • 2020-12-12 03:36

    A dictionary uses UNIQUE keys, so its imposible to have duplicates.

    0 讨论(0)
  • 2020-12-12 03:39

    You can not do that as dict objects have unique keys. You should just the use list of tuple:

    >>> alist = ['key1','key2','key3','key3','key4','key4','key5']
    >>> blist=  [30001,30002,30003,30003,30004,30004,30005]
    
    >>> zip(alist, blist)
    [('key1', 30001), ('key2', 30002), ('key3', 30003), ('key3', 30003), ('key4', 30004), ('key4', 30004), ('key5', 30005)]
    

    If you want to access all the values based on the key, you may use collections.defaultdict as:

    >>> from collections import defaultdict
    
    >>> my_dict = defaultdict(list)
    >>> for k, v in zip(alist, blist):
    ...     my_dict[k].append(v)
    ...
    >>> my_dict
    defaultdict(<type 'list'>, {'key3': [30003, 30003], 'key2': [30002], 'key1': [30001], 'key5': [30005], 'key4': [30004, 30004]})
    

    You can access defaultdict similar to normal dict objects. For example:

    >>> my_dict['key3']
    [30003, 30003]
    
    0 讨论(0)
  • 2020-12-12 03:46

    As dict must use unique keys only, and if you insert same key twice the last one will be stored - this might be something you can use:

    from itertools import groupby
    
    alist = ['key1','key2','key3','key3','key4','key4','key5']
    alist = [i for i, j in groupby(alist)]
    
    blist = [30001,30002,30003,30003,30004,30004,30005]
    blist = [list(j) for i, j in groupby(blist)]
    
    print dict(zip(alist, blist))
    #{'key3': [30003, 30003], 'key2': [30002], 'key1': [30001], 'key5': [30005], 'key4': [30004, 30004]}
    

    If you want to preserve the key order as well you can use OrderedDict:

    from collections import OrderedDict
    print OrderedDict(zip(alist, blist))
    
    0 讨论(0)
提交回复
热议问题