Search code examples
pythonlist-comprehensiondictionary-comprehension

Is there a way to use temporary list variable inside nested dict comprehension?


this is what my dict looks like:

   ranked_imgs = {'d57b26aa-c8f8-4e08-9e8f-8aecd6e952a5': {'small': [],
      'medium': [['https://www.pablo-ruiz-picasso.net/images/works/261.jpg', 1]],
      'large': []},
     'b10ecfdb-f590-4930-9975-aa12dc267f2f': {'small': [],
      'medium': [],
      'large': [['https://www.pablo-ruiz-picasso.net/images/works/3936.jpg', 1]]},......}

This is what I'm trying to do using dict comprehension but it fails because the temporary list is over ridden due to for loop:

dct = {k:[x for x in vv] for k,v in ranked_imgs.items() for vk,vv in v.items()}

or something like this maybe :

dct = {k:sum(vv,[]) for k,v in ranked_imgs.items() for vk,vv in v.items()}

This is what the code will look like with comprehension:

# ranked_imgs_={}

# for k,v in ranked_imgs.items():
#     lst = []
#     for vk,vv in v.items():
#         for url in vv:
#             lst.append(url)
#     ranked_imgs_[k] = lst

I'm curious to know if there is a pythonic way to do this using dict comprehension!


Solution

  • Use chain.from_iterable may be a little better than the answer of @blhsing, it iterates by concatenating v.values():

    from itertools import chain
    result = {k: list(chain.from_iterable(v.values())) for k, v in ranked_imgs.items()}