239

Sorry for this basic question but my searches on this are not turning up anything other than how to get a dictionary's key based on its value which I would prefer not to use as I simply want the text/name of the key and am worried that searching by value may end up returning 2 or more keys if the dictionary has a lot of entries... what I am trying to do is this:

mydictionary={'keyname':'somevalue'}
for current in mydictionary:

   result = mydictionary.(some_function_to_get_key_name)[current]
   print result
   "keyname"

The reason for this is that I am printing these out to a document and I want to use the key name and the value in doing this

I have seen the method below but this seems to just return the key's value

get(key[, default])
4
  • Do you just want to check that 'keyname' exists in the dictionary? Because you do have it already.
    – relet
    Aug 23, 2010 at 7:04
  • 1
    no as I said, need to print it out, it would be iterating through a large number of keys
    – Rick
    Aug 23, 2010 at 7:08
  • currentis the current key, just do print current
    – Moberg
    Feb 24, 2015 at 13:15
  • 4
    How would you get just the 1st key in the dictionary? (no iteration)
    – VISQL
    Apr 28, 2015 at 0:35

15 Answers 15

269

You should iterate over keys with:

for key in mydictionary:
   print "key: %s , value: %s" % (key, mydictionary[key])
2
  • 12
    You can just write for key in mydictionary:
    – blokeley
    Jul 12, 2015 at 10:27
  • 12
    in python 3.6: print (f"key: {key}, value: {mydictionary[key]}")
    – JinSnow
    Jan 24, 2017 at 21:22
122

If you want to access both the key and value, use the following:

Python 2:

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

Python 3:

for key, value in my_dict.items():
    print(key, value)
1
  • 32
    For Python 3: items() instead of iteritems()
    – toshiro92
    Nov 15, 2017 at 14:36
87

The reason for this is that I am printing these out to a document and I want to use the key name and the value in doing this

Based on the above requirement this is what I would suggest:

keys = mydictionary.keys()
keys.sort()

for each in keys:
    print "%s: %s" % (each, mydictionary.get(each))
1
  • I prefer the other answers like the for loop on my_dict.item() or list comprehension like keys = list(my_dict.keys) but just in case someone wants to do this in Python 3 : (line 2) keys = sorted(my_dict.keys()) + add () to print.
    – Honiix
    Dec 12, 2016 at 9:03
79

If the dictionary contains one pair like this:

d = {'age':24}

then you can get as

field, value = d.items()[0]

For Python 3.5, do this:

key = list(d.keys())[0]
5
  • 10
    Python3.5: TypeError: 'dict_items' object does not support indexing
    – Sinux
    Aug 19, 2016 at 2:10
  • 1
    Pretty hackish but d.__iter__().__next__() does a the trick. you get 'age'. You get the same result with this d.items().__iter__().__next__()[0].
    – yoshi
    Nov 21, 2016 at 8:16
  • 2
    In Python3, this works for one pair dicts: key = list(d.keys())[0] Dec 20, 2016 at 13:24
  • If you have a huge dict, using next() is better according to: stackoverflow.com/a/27638751/1488445 Dec 20, 2016 at 13:27
  • works with python 3.11
    – Tech
    May 24 at 16:47
15

keys=[i for i in mydictionary.keys()] or keys = list(mydictionary.keys())

1
  • 1
    Please make sure to use code tags and explain your answer as well. Dec 30, 2014 at 17:25
11

You could simply use * which unpacks the dictionary keys. Example:

d = {'x': 1, 'y': 2}
t = (*d,)
print(t) # ('x', 'y')
2
  • python34: SyntaxError: can use starred expression only as assignment target
    – Tcll
    Jun 22, 2019 at 14:44
  • dang, I use python34 because I can't run anything newer in my windows testing environment.
    – Tcll
    Jun 26, 2019 at 12:07
11

As simple as that:

mydictionary={'keyname':'somevalue'}
result = mydictionary.popitem()[0]

You will modify your dictionary and should make a copy of it first

0
5

Iterate over dictionary (i) will return the key, then using it (i) to get the value

for i in D:
    print "key: %s, value: %s" % (i, D[i])
4

For python 3 If you want to get only the keys use this. Replace print(key) with print(values) if you want the values.

for key,value in my_dict:
  print(key)
3

What I sometimes do is I create another dictionary just to be able whatever I feel I need to access as string. Then I iterate over multiple dictionaries matching keys to build e.g. a table with first column as description.

dict_names = {'key1': 'Text 1', 'key2': 'Text 2'}
dict_values = {'key1': 0, 'key2': 1} 

for key, value in dict_names.items():
    print('{0} {1}'.format(dict_names[key], dict_values[key])

You can easily do for a huge amount of dictionaries to match data (I like the fact that with dictionary you can always refer to something well known as the key name)

yes I use dictionaries to store results of functions so I don't need to run these functions everytime I call them just only once and then access the results anytime.

EDIT: in my example the key name does not really matter (I personally like using the same key names as it is easier to go pick a single value from any of my matching dictionaries), just make sure the number of keys in each dictionary is the same

2

You can do this by casting the dict keys and values to list. It can also be be done for items.

Example:

f = {'one': 'police', 'two': 'oranges', 'three': 'car'}
list(f.keys())[0] = 'one'
list(f.keys())[1] = 'two'

list(f.values())[0] = 'police'
list(f.values())[1] = 'oranges'
2

if you just need to get a key-value from a simple dictionary like e.g:

os_type = {'ubuntu': '20.04'}

use popitem() method:

os, version = os_type.popitem()
print(os) # 'ubuntu'
print(version) # '20.04'
0
names=[key for key, value in mydictionary.items()]
0

if you have a dict like

d = {'age':24}

then you can get key and value by d.popitem()

key, value = d.popitem()
-2

easily change the position of your keys and values,then use values to get key, in dictionary keys can have same value but they(keys) should be different. for instance if you have a list and the first value of it is a key for your problem and other values are the specs of the first value:

list1=["Name",'ID=13736','Phone:1313','Dep:pyhton']

you can save and use the data easily in Dictionary by this loop:

data_dict={}
for i in range(1, len(list1)):
     data_dict[list1[i]]=list1[0]
print(data_dict)
{'ID=13736': 'Name', 'Phone:1313': 'Name', 'Dep:pyhton': 'Name'}

then you can find the key(name) base on any input value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.