Home > Blockchain >  How do I make a list comprehension for 1/3 of a dictionary?
How do I make a list comprehension for 1/3 of a dictionary?

Time:02-11

I am relatively new to python and I started to learn list comprehensions, they seemed a bit complicated at first but start to get intuitive over time. However, there is one problem I could not solve yet

A function receives a dictionary as a parameter with the values looking like this:

datadict = dict(a1=[], a2=[], a3=[], b1=[], b2=[], b3=[], c1=[], c2[], c3=[])

One dictionary with some lists in it, which of course, also contain (float) values all lists have the same len()

The function should seperate the nested lists from the dict according to the letters in to a list of tuples like this:

    list_a = []

for entry in range(len(datadict["a"])):
    list_a.append((
        datadict["a1"][entry],
        datadict["a2"][entry],
        datadict["a3"][entry]
    ))

This works but looks very clunky / hard to read, in my opinion and I wasn't able to make a list comprehension out of it. I tried using the zip() method, tried unpacking, but I couldn't figure it out.

CodePudding user response:

I am not sure I have understood correctly the description of the task. In general, you should make a custom function to embed the logic and use that in the list comprehension. It is way more readable.

Here an example based on your post:

datadict = dict(a1=[1,2,3], a2=[4,5,6], a3=[7,8,9], b1=[0,0,0], b2=[1,1,1], b3=[2,2,2])

def f(d, i):
    return (d['a1'][i], d['a2'][i], d['a3'][i])

result = [f(datadict, n) for n in range(len(datadict['a1']))]

print(result)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
  • Related