Home > Net >  Unable to unpack (loop iterate) for all keys with related pairs (values)
Unable to unpack (loop iterate) for all keys with related pairs (values)

Time:12-31

I know that when creating dict, the key(s) must be unique, but each key can have multiple values, take for example:

This is the dict:

d = {1:a, 2:[a,b,c], 3:[e,f,g]}

What I want to do is to use for loop in python to extract the keys and associated values and turn all into list results, so that I can then make two parallel lists:

Expect result for key:

listA: [1,2,2,2,3,3,3]

Expect result for values:

listB: [a,a,b,c,e,f,g]

For list B, I can do the code to finish it:

listkey = [] #assign a list container
listvalue = [] #assign a list container

for k,v in d.items():
    listkey.append(k)
    listvalue.append(v)

listB = [ item for elem in listvalue for item in elem]

listB result success: [a,a,b,c,e,f,g]

However, for listA,

listA = [ item for elem1 in listvalue for item in elem1]
it just results [1,2,3],but not [1,2,2,2,3,3,3]

I am wondering what's wrong with my code. Can I achieve this by using for loop?

CodePudding user response:

Your sample input is inconsistent (one of the dictionary value is not a list). If it were consistent you could use list comprehensions with nested for loops to get the two lists:

d = {1:['a'], 2:['a','b','c'], 3:['e','f','g']}

listA = [ k for k,v in d.items() for _ in range(len(v)) ]
listB = [ c for v in d.values() for c in v ]

print(listA)  # [1, 2, 2, 2, 3, 3, 3]
print(listB)  # ['a', 'a', 'b', 'c', 'e', 'f', 'g']

The list comprehensions are equivalent to nested for loops:

# [ k for k,v in d.items() for _ in range(len(v)) ]

listA = []
for k,v in d.items():
    for _ in range(len(v)):
        listA.append(k)

# [ c for v in d.values() for c in v ]
listB = []
for v in d.values():
    for c in v:
        listB.append(v)

CodePudding user response:

Simple solution :

In the time that you want add the value use list.extend instead of append:

a = [ 1, 2, 3 ]
b = [ 4, 5, 6 ]

a.extend(b)

The result it that a will put b elemnts in itself. :)

CodePudding user response:

It is often not simple to handle different types as values in a dict. So I have converted the first value into a list in this answer.

You can use nested comprehension and a zip:

d = {1: ['a'], 2: ['a', 'b', 'c'], 3: ['e', 'f', 'g']}

key_value = ((k, v) for k, l in d.items() for v in l)
a, b = zip(*key_value)
print(a) # (1, 2, 2, 2, 3, 3, 3)
print(b) # ('a', 'a', 'b', 'c', 'e', 'f', 'g')

If you do want a and b as lists, you can use instead:

a, b = map(list, zip(*key_value))
# [1, 2, 2, 2, 3, 3, 3]
# ['a', 'a', 'b', 'c', 'e', 'f', 'g']

EDIT: using plain nested for loop:

d = {1: ['a'], 2: ['a', 'b', 'c'], 3: ['e', 'f', 'g']}

a, b = [], []
for key, lst in d.items():
    for val in lst:
        a.append(key)
        b.append(val)

print(a) # [1, 2, 2, 2, 3, 3, 3]
print(b) # ['a', 'a', 'b', 'c', 'e', 'f', 'g']
  • Related