How to acess the values in the dictionay?#dict={"one":1,"two":2}.I want print one,two by acessing 1,2. is it possible.pls help. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to acess the values in the dictionay?#dict={"one":1,"two":2}.I want print one,two by acessing 1,2. is it possible.pls help.

beginner

16th Apr 2020, 8:17 AM
Lavanya T
Lavanya T - avatar
3 Answers
+ 2
You can use dictionary `items` method, it returns pairs of key-value for each dictionary item. my_dict = { 'one' : 1, 'two' : 2 } elms = my_dict.items() #print(elms) # uncomment to see what it's like for elm in elms: if elm[1] == 2: print(elm[0]) break
16th Apr 2020, 9:31 AM
Ipang
+ 2
You would like to access a key by its value instead of the value by its key? Do I understand that right? Maybe you could do sth like this: tmp = list(dict.items()) Than you get a list of tuples: 1st element of each tuple is the key, the remaining ones are the values You could loop through tmp until the values 1 and 2 are found and than print their key which will be the 1st element of the tuple
16th Apr 2020, 8:32 AM
Lisa
Lisa - avatar
+ 2
If you're dict has strictly only all integers in a range, you could be more efficient by building a reverse list of your dict (so later access will be quickest): rev_dict = sorted(dict.keys(),key=lambda k: dict[k]) So, if the range start at n, you just have to do rev_dict[x-n] to get the key of the value x ;)
16th Apr 2020, 3:32 PM
visph
visph - avatar