简体   繁体   中英

Create a dict based on key-value pairs without using a for loop

I still have a solution but wonder if there is a more pythonic version with in-built Python tools.

  • The goal would be to avoid the for loop.
  • Does Python offer a technique (package) to solve this?

I have 2 lists of the same length, one representing keys (with possible duplicates) and the other the values.

keys = list('ABAA')
vals = [1, 2, 1, 3]

The expected result:

{
    'A': [1, 1, 3],
    'B': [2]
}

My working solution (with Python 3.9):

result = {}

for k, v in zip(keys, vals):
    # create new entry with empty list
    if k not in result:
        result[k] = []

    # store the value
    result[k].append(v)

print(result)

Very similar to your solution (which is great btw), but you could zip the lists and use dict.setdefault :

out = {}
for k,v in zip(keys,vals):
    out.setdefault(k, []).append(v)

Output:

{'A': [1, 1, 3], 'B': [2]}

Can use this:

keys = list('ABAA')
vals = [1, 2, 1, 3]

d = {}
for key in set(keys):
    d[key] = [vals[i] for i in range(len(keys)) if keys[i] == key]

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