4

Is there a way to get the value of the key, not the key value in a dictionary? for example:

d = {"testkey": "testvalue"}
print(d.get("testkey"))
#OUTPUT: "testvalue"

Is there a way to get the String "testkey"? I will have no way of knowing what the String returned will be in the end. Would it be more beneficial to use a list instead of a dictionary?

Aaron
  • 992
  • 3
  • 15
  • 33
  • Nomenclature note: in the dictionary `{"foo": "bar"}`, "foo" is the _key_ and "bar" is the _value_. Talking about "key values" and "values of keys" is a good way to get everyone confused. – senshin Dec 07 '15 at 19:23

2 Answers2

4

You are looking for the keys() function (used as d.keys()).
You may also use this:

for key in d:
   print "key: %s , value: %s" % (key, d[key])

for all the information.

Idos
  • 15,053
  • 14
  • 60
  • 75
3

First note that dicts are not intended to be used this way. Anyway you can use a simple list comprehension and the items() method, since there could be more than one result:

[key for key, val in d.items() if val == someValue]

For instance:

>>> myDict = {1:"egg", "Answer":42, 8:14, "foo":42}
>>> [key for key, val in myDict.items() if val == 42]
['Answer', 'foo']
elegent
  • 3,857
  • 3
  • 23
  • 36