0

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 :)

Kyle Me
  • 336
  • 2
  • 5
  • 13

3 Answers3

1
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.

m.wasowski
  • 6,329
  • 1
  • 23
  • 30
0

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
Alex Koukoulas
  • 998
  • 1
  • 7
  • 21
0

Why don't you try:

for key, value in d.iteritems():
    print(key+value)
praba230890
  • 2,192
  • 21
  • 37