+ 1

how do i get the value inside this list???

I want to get the "anoTrabalho", how do I get it? d = { "Pedro": {"salario": 800, "anoTrabalho": 3}, "Ana": {"salario": 1200, "anoTrabalho": 2}, "Luis": {"salario": 200, "anoTrabalho": 0}, "Joao": {"salario": 900, "anoTrabalho": 4} }

8th Feb 2023, 2:27 PM
sunshine - avatar
6 Answers
+ 13
sunshine , we can also get the reqired value from the key *anoTrabalho* without using a loop: name = input() print(d[name]['anoTrabalho']) # using bracket notation. this will crash if the input name is not a key in the dict. # or: print(d.get(name, {}).get('anoTrabalho')) # using <dictionary>.get(): in case of the key could not be found, there is a workaround to return *None*.
8th Feb 2023, 6:09 PM
Lothar - avatar
+ 5
d.items() contains key-value pairs of string (name) and a dictionary (salary & year of work). So we can refer the desired dictionary item using the already known key name ("anoTrabalho") for k, v in d.items(): print( k, v[ 'anoTrabalho' ] ) Mind that the key is case sensitive, must match exactly. (Edit) It's a nested dictionary BTW, not a `list`. If you don't mind, you can update the title of the post.
8th Feb 2023, 3:38 PM
+ 4
You have a nested dictionary, so you need to iterate through the keys of the first dictionary to get to the inside dictionary. for name in d:     print(d[name]["anoTrabalho"]) The "for name in d" will assign the key to variable 'name' on each iteration. Then when printing, the d[name] will get you to the values of the first dictionary which is the nested dictionary. The second bracket ["anoTrabalho"] will provide the value for that key of the inner dictionary.
9th Feb 2023, 2:50 AM
+ 2
sunshine I could be wrong, but it could be because "worker" isn't in the variable "d". Also, you should provide what programming language you're using this in.
8th Feb 2023, 3:18 PM
Katz321Juno - avatar
+ 2
you can convert the result of worker to a list and print the second item . for k in d: print( list( d.get(k) )[1])
8th Feb 2023, 3:27 PM
Bahha🐧 - avatar
+ 2
this: for worker in d: print(d[worker]["anoTrabalho"])
8th Feb 2023, 11:26 PM
Bob_Li - avatar