简体   繁体   中英

Adding values to dictionary keys from a list of lists

I have the following list and dictionary:

list = [[1,2,2],[2,3,3],[3,4,4]
dict = {1:[], 2:[], 3:[]}

Let's say I wanted to append all values that proceed dict[keys] into their respective keys such that:

dict = {1:[2,2], 2:[3,3], 3:[4,4]}

I've attempted using multiple loops to accomplish this. However whenever I do that all values get searched and appended to each dict[key] simultaneously. Any help would be appreciated!

l = [[1,2,2],[2,3,3],[3,4,4]]

# last key wins 
d = {sublist[0]:sublist[1:] for sublist in l}

print(d)

You construct the dictionary from your lists elements. Do not use list or dict as names, they shadow the built-ins.

sublist[0] is the first element, sublist[1:] are the rest of the elements of each item in l.

More about the syntax used here: PEP 274: Dict Comprehensions

Outputs:

{1: [2, 2], 2: [3, 3], 3: [4, 4]}     # last key wins (no duplicates present)

If you need to merge as well, you can use:

# merging keys into values as list of sublists
l = [[2,2,2],[2,3,3],[3,4,4]]
d1 = {}
for sub in l:
    # creates dict of { key: [ [int,...], [int,...] ], ... } for same keys
    d1.setdefault(sub[0],[]).append(sub[1:]) 

or by flattening:

# merging keys into values as flattened list
d2 = {}
for sub in l:
    # creates dict of { key: [ int,...,int,... ], ... } for same keys
    d2.setdefault(sub[0],[]).extend(sub[1:]) 

Outputs:

{2: [[2, 2], [3, 3]], 3: [[4, 4]]}    # merging keys into values as list of sublists

{2: [2, 2, 3, 3], 3: [4, 4]}          # merging keys into values as flattened list

For merging I used dict.setdefault() you might want to take a peek at collections.defaultdict() which I get assured is better suited.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM