Home > Back-end >  Retrieve value from dictionary with list
Retrieve value from dictionary with list

Time:05-12

I see so many questions but not found any with dictionary like that:

I have this dict:

my_dict = {
    'og_min': 'https://www.example.com/assets/images/empreendimentos/listing-varanda-vila-ema.png?_=1000',
    'images_sobre_o_produto': ['https://www.example.com/assets/images/enterprises/varanda-vila-ema/fachada.png?_=1000', 'https://www.example.com/assets/images/enterprises/retrato-by-dialogo/living.png?_=1000']}

How can iterate over that dict to get all urls one at time?

If I use something like:

for values in my_dict.values():
    print(values)
    for value in values:
        print(value)

The first value from og_min key is split, how to avoid that?

CodePudding user response:

The fact there is you have a dictionary, with two keys. One key is a string, and the other holds a list.

So you can do something like this:

for key, val in my_dict.items():
    if type(val) is list:
        for url in val:
            print(url)
    if type(val) is str:
        print(val)

That will give you the url's output you are looking for.

Of course this code is assuming that you have to type of values, a string and a list type, and the string value holds a url and the list type contains a list of url's.

  • Related