简体   繁体   中英

Python - Dictionaries - Print a key given the value

I'm new to programming, sorry if this is a silly question. From a dictionary (I'm aware there are other ways to do this), I want to be able to print out the value (or key, I get them confused) of a dictionary item. For example: d = {'print this':'given this'}

>>> d['given this']
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    d['given this']
KeyError: 'given this'
>>> 

However, this works.

>>> d['print this']
'given this'
>>> 

So I know there must be a way to get it to give me that variable. One thing I am confused on is this.

>>> for i in d:
    print(i + d[i])


print thisgiven this
>>> 

How come I am able to print out both of the strings when I have a for loop?

Sorry if I did not post correctly, please tell me what I should change to make my question easier to answer.

Also please note, I have tried finding out the answer to this myself. I briefly learned about the "get" method, but I was having trouble getting it to do what I wanted to do. Thanks :)

print [(key, value) for key, value in d.items ()
           if value == value_you_search_for]

Keep in mind, that this can give you zero, one or more items - while keys are unique, values don't need to be.

You can't directly access a key by a given value. What you could do is this:

for key, value in d.iteritems() :
    print value,key

Why don't you try:

for key, value in d.iteritems():
    print(key+value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM