Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dictionary put values of keys into a list where the keys are in another list

I have a dictionary which looks like

a = {32: [2230], 37265: [2218], 51: [2223], 164: [2227], 3944: [2224]}

however, values in a could contain multiple elements, like

a = {32: [2200, 2230], 37265: [2201, 2218], 51: [2223], 164: [2227], 3944: [2224]}

I have a list that stores the keys in a in groups,

b = [[32, 51, 164], [3944, 37265]]

now I want to get values of keys in each group in another list,

        clusters = []
        for key_group in b:
            group = []

            for key in key_group:
                group.extend(a[key])

            if len(group) > 1:
                clusters.append(group) 

so the final list looks like,

clusters = [[2230, 2223, 2227], [2224, 2218]]

if a contains multiple elements in a value list, clusters looks like,

clusters = [[2200, 2230, 2223, 2227], [2224, 2201, 2218]]

I am wondering what's the best way to do this.

Also in case when b contains list(s) which has only one value/key, and if this key maps to a single element list in a, this list will be ignored,

a = {32: [2200, 2230], 37265: [2201, 2218], 51: [2223], 164: [2227], 3944: [2224]}

b = [[32, 51, 164], [3944], [37265]]

while 3944 maps to [2224], which will be ignored, but 37265 maps to [2201, 2218], which will be kept, since len([2201, 2218]) > 1. clusters will look like the following in this case,

clusters = [[2200, 2230, 2223, 2227], [2201, 2218]]         
like image 555
daiyue Avatar asked Dec 21 '25 14:12

daiyue


1 Answers

Assuming your values in a are always just a list with a single element, then it is a simple nested list comprehension:

[[a[k][0] for k in sublist] for sublist in b]
# [[2230, 2223, 2227], [2224, 2218]]

Since you've now clarified the values of a can be lists with multiple elements, you can use itertools.chain.from_iterable to flatten the lists returned and give your desired output:

from itertools import chain
[list(chain.from_iterable(a[k] for k in sublist)) for sublist in b]
# [[2200, 2230, 2223, 2227], [2224, 2201, 2218]]
like image 63
Chris_Rands Avatar answered Dec 24 '25 04:12

Chris_Rands



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!