Access dict within list

2

How do I access the dictionary where it contains the Portuguese language from the list below?

To access the key: variavel.foreign_names , but I would like to get the values that are inside the dictionary with Portuguese language (the dictionary will not always be the last one.)

"foreignNames":[  
    {  
      "name":"Archange Avacyn",
      "language":"French",
      "multiverseid":411061
    },
    {  
      "name":"Erzengel Avacyn",
      "language":"German",
      "multiverseid":410731
    },
    {  
      "name":"Arcangelo Avacyn",
      "language":"Italian",
      "multiverseid":411391
    },
    {  
      "name":"大天使アヴァシン",
      "language":"Japanese",
      "multiverseid":411721
    },
    {  
      "name":"대천사 아바신",
      "language":"Korean",
      "multiverseid":412051
    },
    {  
      "name":"Arcanjo Avacyn",
      "language":"Portuguese (Brazil)",
      "multiverseid":412381
    }
    
asked by anonymous 16.01.2017 / 18:52

1 answer

4

You can do the following:

dic = {"foreignNames":[  
    {  
      "name":"Archange Avacyn",
      "language":"French",
      "multiverseid":411061
    },
    {  
      "name":"Erzengel Avacyn",
      "language":"German",
      "multiverseid":410731
    },
    {  
      "name":"Arcangelo Avacyn",
      "language":"Italian",
      "multiverseid":411391
    },
    {  
      "name":"大天使アヴァシン",
      "language":"Japanese",
      "multiverseid":411721
    },
    {  
      "name":"대천사 아바신",
      "language":"Korean",
      "multiverseid":412051
    },
    {  
      "name":"Arcanjo Avacyn",
      "language":"Portuguese (Brazil)",
      "multiverseid":412381
    }
]}

def find_lang(lingua):
    for i in dic['foreignNames']:
        if(i['language'].lower().startswith(lingua.lower())):
            return i
    return None

lang = find_lang('portuguese')
print(lang) # {'name': 'Arcanjo Avacyn', 'language': 'Portuguese (Brazil)', 'multiverseid': 412381}

DEMONSTRATION

Or, if you prefer without using a function:

...
lingua = 'Portuguese'

for i in dic['foreignNames']:
    if(i['language'].lower().startswith(lingua.lower())):
        print(dic_lingua) # {'name': 'Arcanjo Avacyn', 'language': 'Portuguese (Brazil)', 'multiverseid': 412381}
        break
else: # caso o for acima nao tenha sofrido break
    print('não encontrado')

Note that I am comparing lower() to fetching case insensitive , I am assuming that it will come from some external input, you can remove it if you see that it is misused (thus: if(i['language'].startswith(lingua)) ), if you want to make a precise comparison (same words exactly) you do, if(i['language'] == lingua)

A way with list comprenssion, but if you ask me I prefer the above solutions:

...
lingua = 'Portuguese'
dic_lingua = [x for x in dic['foreignNames'] if x['language'].startswith(lingua)]

if dic_lingua: # verificar se a lista resultante traz alguma entrada
    print(dic_lingua[0])
else:
    print('não encontrado')
    
16.01.2017 / 18:58