[python] How can I get dictionary key as variable directly in Python (not by searching from value)?

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

This question is related to python dictionary key

The answer is


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

d = {'x': 1, 'y': 2}
t = (*d,)
print(t) # ('x', 'y')

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.


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


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'

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

As simple as that:

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

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


This code below is to create map to manager players point. The goal is to concatenate the word "player" with a sequential number.

players_numbers = int(input('How many girls will play? ')) #First - input receive a input about how many people will play

players = {}  
counter = 1

for _ in range(players_numbers): #sum one, for the loop reach the correct number
    player_dict = {f'player{counter}': 0} #concatenate the word player with the player number. the initial point is 0.
    players.update(player_dict) #update the dictionary with every player
    counter = counter + 1
    print(players)

Output >>> {'player1': 0, 'player2': 0, 'player3': 0}...


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

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)

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'

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


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)

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]

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python

Examples related to key

How do I check if a Key is pressed on C++ Map<String, String>, how to print both the "key string" and "value string" together Python: create dictionary using dict() with integer keys? SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch How to get the stream key for twitch.tv How to get key names from JSON using jq How to add multiple values to a dictionary key in python? Initializing a dictionary in python with a key value and no corresponding values How can I sort a std::map first by value, then by key?