+ 2

How to call the key of an element in a dictionary?

Is there a function or an attribute to return the key of a certain element in a dictionary in python when the element is known? If so... what is it? Any help will be appreciated:)

16th Mar 2018, 1:07 PM
Pasindu Perera
Pasindu Perera - avatar
8 Respuestas
+ 2
'keys' method take no arguments. So, in my code, 'for i in ab' is same as 'for i in ab.keys()'. If you want to search for values in dictionary, use ab.values(). Want to get both? use ab.items().
17th Mar 2018, 5:26 AM
Sylar
+ 4
ab = {'Names':'James','Age':22} for i in ab: if ab[i] == 22: print(i) Is it what you want?
16th Mar 2018, 2:15 PM
Sylar
+ 3
Yes.... that 'i'. is there a function or an attribute in python to get it? like... index attribute in lists? Thanks for the reply:)
17th Mar 2018, 1:46 AM
Pasindu Perera
Pasindu Perera - avatar
+ 3
Yes thank you. That's what I wanted to know.....☺
17th Mar 2018, 3:54 AM
Pasindu Perera
Pasindu Perera - avatar
+ 3
so.... in your code: { for i in ab: } == ab.keys(22) { if ab[i] == 22: } { print(i) } ???
17th Mar 2018, 3:57 AM
Pasindu Perera
Pasindu Perera - avatar
+ 3
nameofdict.get(nameofkey)
18th Mar 2018, 11:58 PM
Julian
Julian - avatar
+ 2
In my code, 'i' is the key-name string. i.e 'i' may be 'Names' or 'Age'. You can call dictionary key-names via like this: ab.keys() . That's dictionary's method to grab key-names.
17th Mar 2018, 3:44 AM
Sylar
+ 2
okay☺ got it cheers and thanks....
17th Mar 2018, 7:12 AM
Pasindu Perera
Pasindu Perera - avatar