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

Time:02-21

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)

CodePudding user response:

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]}

CodePudding user response:

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]
  • Related