How to print a dictionary's key? - python

I would like to print a specific Python dictionary key:
mydic = {}
mydic['key_name'] = 'value_name'
Now I can check if mydic.has_key('key_name'), but what I would like to do is print the name of the key 'key_name'. Of course I could use mydic.items(), but I don't want all the keys listed, merely one specific key. For instance I'd expect something like this (in pseudo-code):
print "the key name is", mydic['key_name'].name_the_key(), "and its value is", mydic['key_name']
Is there any name_the_key() method to print a key name?
Edit:
OK, thanks a lot guys for your reactions! :) I realise my question is not well formulated and trivial. I just got confused because I realised 'key_name' and mydic['key_name'] are two different things and I thought it would be incorrect to print the 'key_name' out of the dictionary context. But indeed I can simply use the 'key_name' to refer to the key! :)

A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the keys() method, which gives you a python list of all the keys, and you have the iteritems() method, which returns key-value pairs, so
for key, value in mydic.iteritems() :
print key, value
Python 3 version:
for key, value in mydic.items() :
print (key, value)
So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.

Additionally you can use....
print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values

Hmm, I think that what you might be wanting to do is print all the keys in the dictionary and their respective values?
If so you want the following:
for key in mydic:
print "the key name is" + key + "and its value is" + mydic[key]
Make sure you use +'s instead of ,' as well. The comma will put each of those items on a separate line I think, where as plus will put them on the same line.

dic = {"key 1":"value 1","key b":"value b"}
#print the keys:
for key in dic:
print key
#print the values:
for value in dic.itervalues():
print value
#print key and values
for key, value in dic.iteritems():
print key, value
Note:In Python 3, dic.iteritems() was renamed as dic.items()

The name of the key 'key_name' is 'key_name', therefore
print('key_name')
or whatever variable you have representing it.

In Python 3:
# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}
# To print a specific key (for example key at index 1)
print([key for key in x.keys()][1])
# To print a specific value (for example value at index 1)
print([value for value in x.values()][1])
# To print a pair of a key with its value (for example pair at index 2)
print(([key for key in x.keys()][2], [value for value in x.values()][2]))
# To print a key and a different value (for example key at index 0 and value at index 1)
print(([key for key in x.keys()][0], [value for value in x.values()][1]))
# To print all keys and values concatenated together
print(''.join(str(key) + '' + str(value) for key, value in x.items()))
# To print all keys and values separated by commas
print(', '.join(str(key) + ', ' + str(value) for key, value in x.items()))
# To print all pairs of (key, value) one at a time
for e in range(len(x)):
print(([key for key in x.keys()][e], [value for value in x.values()][e]))
# To print all pairs (key, value) in a tuple
print(tuple(([key for key in x.keys()][i], [value for value in x.values()][i]) for i in range(len(x))))

Since we're all trying to guess what "print a key name" might mean, I'll take a stab at it. Perhaps you want a function that takes a value from the dictionary and finds the corresponding key? A reverse lookup?
def key_for_value(d, value):
"""Return a key in `d` having a value of `value`."""
for k, v in d.iteritems():
if v == value:
return k
Note that many keys could have the same value, so this function will return some key having the value, perhaps not the one you intended.
If you need to do this frequently, it would make sense to construct the reverse dictionary:
d_rev = dict(v,k for k,v in d.iteritems())
Update for Python3: d.iteritems() is not longer supported in Python 3+ and should be replaced by d.items()
d_rev = {v: k for k, v in d.items()}

# highlighting how to use a named variable within a string:
mapping = {'a': 1, 'b': 2}
# simple method:
print(f'a: {mapping["a"]}')
print(f'b: {mapping["b"]}')
# programmatic method:
for key, value in mapping.items():
print(f'{key}: {value}')
# yields:
# a 1
# b 2
# using list comprehension
print('\n'.join(f'{key}: {value}' for key, value in dict.items()))
# yields:
# a: 1
# b: 2
Edit: Updated for python 3's f-strings...

Make sure to do
dictionary.keys()
rather than
dictionary.keys

import pprint
pprint.pprint(mydic.keys())

Or you can do it that manner:
for key in my_dict:
print key, my_dict[key]

dict = {'name' : 'Fred', 'age' : 100, 'employed' : True }
# Choose key to print (could be a user input)
x = 'name'
if x in dict.keys():
print(x)

What's wrong with using 'key_name' instead, even if it is a variable?

Probably the quickest way to retrieve only the key name:
mydic = {}
mydic['key_name'] = 'value_name'
print mydic.items()[0][0]
Result:
key_name
Converts the dictionary into a list then it lists the first element which is the whole dict then it lists the first value of that element which is: key_name

I'm adding this answer as one of the other answers here (https://stackoverflow.com/a/5905752/1904943) is dated (Python 2; iteritems), and the code presented -- if updated for Python 3 per the suggested workaround in a comment to that answer -- silently fails to return all relevant data.
Background
I have some metabolic data, represented in a graph (nodes, edges, ...). In a dictionary representation of those data, keys are of the form (604, 1037, 0) (representing source and target nodes, and the edge type), with values of the form 5.3.1.9 (representing EC enzyme codes).
Find keys for given values
The following code correctly finds my keys, given values:
def k4v_edited(my_dict, value):
values_list = []
for k, v in my_dict.items():
if v == value:
values_list.append(k)
return values_list
print(k4v_edited(edge_attributes, '5.3.1.9'))
## [(604, 1037, 0), (604, 3936, 0), (1037, 3936, 0)]
whereas this code returns only the first (of possibly several matching) keys:
def k4v(my_dict, value):
for k, v in my_dict.items():
if v == value:
return k
print(k4v(edge_attributes, '5.3.1.9'))
## (604, 1037, 0)
The latter code, naively updated replacing iteritems with items, fails to return (604, 3936, 0), (1037, 3936, 0.

I looked up this question, because I wanted to know how to retrieve the name of "the key" if my dictionary only had one entry. In my case, the key was unknown to me and could be any number of things. Here is what I came up with:
dict1 = {'random_word': [1,2,3]}
key_name = str([key for key in dict1]).strip("'[]'")
print(key_name) # equal to 'random_word', type: string.

Try this:
def name_the_key(dict, key):
return key, dict[key]
mydict = {'key1':1, 'key2':2, 'key3':3}
key_name, value = name_the_key(mydict, 'key2')
print 'KEY NAME: %s' % key_name
print 'KEY VALUE: %s' % value

key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])

If you want to get the key of a single value, the following would help:
def get_key(b): # the value is passed to the function
for k, v in mydic.items():
if v.lower() == b.lower():
return k
In pythonic way:
c = next((x for x, y in mydic.items() if y.lower() == b.lower()), \
"Enter a valid 'Value'")
print(c)

Related

Replace key references by corresponding values in dict values

In the following dictionary, a user can refer to a key as a variable for defining another value:
d = {'a_key': 'a_value', 'b_key': 'a_key+1'}
I have to replace these references by the corresponding values, in order to obtain this desired output:
d = {'a_key': 'a_value', 'b_key': 'a_value+1'}
I thought it would be easy, but this one drives crazy since a few hours. I got to this code:
for k in d.keys():
print("key: " + k)
print("value: " + d[k])
for v in d.values():
print("value_before: " + v)
v = v.replace(k, d[k])
print("value_after: " + v)
print(d)
The output is:
key: a_key
value: a_value
value_before: a_value
value_after: a_value
value_before: a_key+1
value_after: a_value+1
key: b_key
value: a_key+1 # WHY??
value_before: a_value
value_after: a_value
value_before: a_key+1
value_after: a_key+1
{'a_key': 'a_value', 'b_key': 'a_key+1'}
As we see, the first iteration seems to do the job, before it is cancelled by the second one. I just don't unserstand why. I also tried to adapt the very specific answers to that question: Replace values in dict if value of another key within a nested dict is found in value, but to no avail. I'm looking for a general answer to: how to get the desired output?
From a theoretic point of view, I would also like to understand why the "b_value" is reset to a_key+1. Thanks.
The problem is that you are modifying temporary variable v but you are not placing the modified values back in the dictionary.
Try replacing :
for v in d.values():
v = v.replace(k, d[k])
with:
for r,v in d.items():
d[r] = v.replace(k, d[k])

How to get my hashmap to return multiple values to one key in python

I am at my wit's end. I've been learning Python from LearningPythontheHardWay, I was learning well until exercise 39 with the dictionary module hashmap.
I can get it to work with just key, value pairs. I want this module to allow me to work with multiple values to each key. There was another question on here like this but it wasn't answered completely, or I did not understand the answer. I want to learn Python, but this is really restricting me from progressing and I need help.
def get(aMap, key, default=None):
"""Gets the value in a bucket for the given key, or the default."""
bucket = get_bucket(aMap, key)
i, k, v = get_slot(aMap, key, default=default)
for k in enumerate(bucket):
while v:
return v #returns the value of the key!!!
This get function from the module does not work. I can get Python to list the entire dictionary with multiple key values using list function, so I know the values are in there through my set function:
def set(aMap, key, value):
"""Sets the key to the value, replacing any existing value."""
bucket = get_bucket(aMap, key)
i, k, v = get_slot(aMap, key)
bucket.append((key, value))
I know I'm supposed to get a value list in there and then loop through the list if the key should contain more than one value.
I am having a hard time putting this in code language. The bucket contains the list for the tuple (k,v) pairs and the k should contain a list of v.
So far I can only get one value to appear and it stops. Why does the while loop stop?
Thank you.
EDIT: For more clarity, I want to return multiple values if I input a single key that has more than one value.
cities = hashmap.new()
hashmap.set(cities, 'MH', 'Mumbai')
hashmap.set(cities, 'MH', 'Pune')
hashmap.set(cities, 'MH', 'Augu')
print ("%s" % hashmap.get(cities, 'MH'))
This should return all those values out.
Keep in mind that the "return" keyword always terminates the function(callee) and jump to caller, that's why you can not "return multiple value by using return keyword multiple times".
The workaround are
return a list or tuple(as suggested by #terry-jan-reedy)
implement as Iterators & Generators
A hashmap is a hash by key (means efficient research algorithm) not by value ...
If I understand correctly you seems to fear that the value may be a complex type.
The simplest dictionary is
{"key1":"Value1", "key2":"Value2"}
Where you can also have:
{"key1": [1,2,3,"hello"], "key2": A_class_instance, "key3": range(500) }
then value should be as complex as you want ...
now if you want to build a hash map of values (for filtering for instance)
you may glance at the following code:
Mydic = {}
for k,v in My_huge_key_value_table_of_couples:
try:
Mydic[k].append(v)
except KeyError:
Mydic[k] = [v]
to build a hash map with multiple value in each values
Now To access it with default value
just
def get (amap, key, default=None):
try: return amap[key]
except KeyError: return default
to strictly answer the question
Edit to match your hashmap edit..
If you write hashmap.new() ... you had imported a hashmap module, yours ?
I suppose there hashmap is a dictionary
cities = {} # create the dictionary
def set (amap, key, value):
try: amap[key].append(value) #append the element if key already exists
except KeyError: amap[key] = [value] # Init the first element
set(cities, , 'MH', 'Mumbai')
set(cities, 'MH', 'Pune')
set(cities, 'MH', 'Augu')
def get (amap, key, default=None):
try: return ','.join(amap[key]) # You must return a string not a list
except KeyError: return default # in case of no key
print get(cities, 'MH')
Supposing hashmap exists ;-) as a tuple of unfixed limit tuples.
in the form:
((k,v),(k1,v1,v2), ... )
Your code is a little bit hard to follow.
Keep in mind also that a tuple is static and stand for static data.
Manipulating tuple as you want should be tricky
def get_h(h, k):
# like that ?
def get_bucket(h,k):
# supposition get_bucket return the tuple (key, value1, value2) as a list: [ value1, value2 ] ?
# even if your line bucket.append((key, value)) in the set function is a non sens !
#it will produce [ value1, value2, (key, value)] result
for f in h:
if f[0] == k: return list(f[1:])
bucket = get_bucket(aMap, key)
but be carefull at this level you cannot do
print ("%s" % get_h(cities, 'MH'))
# ^^^^^^^^^^^^^^^^^^^--------> is a list not a string
print ("%s" % ','.join(get_(cities, 'MH'))) # is correct
Tips: You should use the IDLE .. to test things .. it is often very usefull
I think your first question is how to store multiple values for each key. We can try storing the values as a list. I think the changes you need to make are mainly to the functions set().
def set(aMap, key, value):
"""Sets the key to the value, multiple values for each key"""
#i, k, v = get_slot(aMap, key)
bucket = get_bucket(aMap, key)
i, k, vlist = get_slot(aMap, key)
if i >= 0:
# if key exists, append value
vlist.append(value)
else:
# the key does not exist, append a key and list. The list stores the values
bucket.append((key, [value]))
The [value] refers to the list.
To get the values, we can change the get function to:
def get(aMap, key, default=None):
"""Gets the values in a bucket for the given key, or the default."""
i, k, vlist = get_slot(aMap, key, default=default)
return vlist

How can you print a key given a value in a dictionary for Python?

For example lets say we have the following dictionary:
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
How can you print a certain key given its value?
print(dictionary.get('A')) #This will print 4
How can you do it backwards? i.e. instead of getting a value by referencing the key, getting a key by referencing the value.
I don't believe there is a way to do it. It's not how a dictionary is intended to be used...
Instead, you'll have to do something similar to this.
for key, value in dictionary.items():
if 4 == value:
print key
In Python 3:
# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}
# To print a specific key (for instance the 2nd key which is at position 1)
print([key for key in x.keys()][1])
Output:
Y
The dictionary is organized by: key -> value
If you try to go: value -> key
Then you have a few problems; duplicates, and also sometimes a dictionary holds large (or unhashable) objects which you would not want to have as a key.
However, if you still want to do this, you can do so easily by iterating over the dicts keys and values and matching them as follows:
def method(dict, value):
for k, v in dict.iteritems():
if v == value:
yield k
# this is an iterator, example:
>>> d = {'a':1, 'b':2}
>>> for r in method(d, 2):
print r
b
As noted in a comment, the whole thing can be written as a generator expression:
def method(dict, value):
return (k for k,v in dict.iteritems() if v == value)
Python versions note: in Python 3+ you can use dict.items() instead of dict.iteritems()
target_key = 4
for i in dictionary:
if dictionary[i]==target_key:
print(i)
Within a dictionary if you have to find the KEY for the highest VALUE please do the following :
Step 1: Extract all the VALUES into a list and find the Max of list
Step 2: Find the KEY for the particular VALUE from Step 1
The visual analyzer of this code is available in this link : LINK
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
lis=dictionary.values()
print(max(lis))
for key,val in dictionary.items() :
if val == max(lis) :
print("The highest KEY in the dictionary is ",key)
I think this is way easier if you use the position of that value within the dictionary.
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
# list out keys and values separately
key_list = list(dictionary.keys())
val_list = list(dictionary.values())
# print key with val 4
position = val_list.index(4)
print(key_list[position])
# print key with val 6
position = val_list.index(6)
print(key_list[position])
# one-liner
print(list(my_dict.keys())[list(my_dict.values()).index(6)])
Hey i was stuck on a thing with this for ages, all you have to do is swap the key with the value e.g.
Dictionary = {'Bob':14}
you would change it to
Dictionary ={1:'Bob'}
or vice versa to set the key as the value and the value as the key so you can get the thing you want

Populating a dictionary with upper case values of the keys already present in the dictionary

I have a dict variable d containing character-character key value pair. All these characters are in smaller case. I want to store the corresponding upper case character mapping as key value pairs too.
The dictionary consists of these entries
d[q]='a'
d[w]='s'
d[e]='d'
d[r]='f'
d[t]='g'
I want to have this also
d[Q]='A'
d[W]='S'
d[E]='D'
d[R]='F'
d[T]='G'
How can I do this ?
Use a generator expression to update your dictionary:
d.update({k.upper(): v.upper() for k, v in d.iteritems()})
or, for Python 3:
d.update({k.upper(): v.upper() for k, v in d.items()})
or, for Python 2.6 and earlier:
d.update([(k.upper(), v.upper()) for k, v in d.iteritems()])
This loops over all key-value pairs in d then adds a corresponding uppercase key-value pair.
If you are going to have a lot of values it may be better to create your own dictionary class that calls .lower on all of the items passed to getitem so like so:
class CustomDict(dict):
def __getitem__(self, key):
if key.lower() == key:
return super(CustomDict, self).__getitem__(key.lower()).lower()
else:
return super(CustomDict, self).__getitem__(key.lower()).upper()
d = CustomDict({"a" : "q" , "s":"w" , "d":"e", "f": "r"})
print d["A"] #prints 'Q'
print d["s"] #prints 'w'
This makes it so you don't have to have 2 similar references to 2 similar values.

modify a dictionary

I need to modify a dictionary. I have a dictionary with integer values and want to replace each value with the fraction of the total of all values, eg.:
census={a:4, b:1, c:3}; turnIntoFractions(census), should then print {a:0.5, b:0,125 ,c:0,375 }
I was thinking something like:
def turnIntoFractions:
L=d.keys()
total=sum(L)
F=[]
for count in L:
f.append(float(count/float(total))
return F
I'm kind of stuck, and it isn't working..
You can use dictionary comprehension.
def turnIntoFractions(d):
total = float(sum(d.values()))
return {key:(value/total) for key,value in d.items()}
Your first problem is that you are doing the sum of the keys, not the values:
total = sum(d.values())
Now, you can just modify the dictionary inline, instead of putting it into a new list:
for key in d.keys():
d[key] /= total # or d[key] = d[key] / total
My previous code goes through each key, retrieves the value, then divides by total, and then finally stores it back into d[key].
If you want a new dictionary returned, instead of just modifying the existing one, you can just start out with e = d.copy(), then use e instead.
You seem to want to edit the dict in place, but your code returns a new object, which is actually better practice.
def turnIntoFractions(mydict):
values=d.values()
total=float(sum(values))
result = {}
for key, val in mydict.items():
result[key] = val/total
return result
your code has the right idea, but also a few small mistakes.
here's a working code:
def turnIntoFractions(d):
L=d.values()
total=sum(L)
f=[]
for count in L:
f.append(float(count/float(total)))
return f
census={'a':4, 'b':1, 'c':3}
print(turnIntoFractions(census))
note that python is case sensitive so f is not the same as F, and also keys that are strings need to be quoted
Use dictionary comprehension
sum = float(sum(census.itervalues()))
newDict = {k : (v / sum) for k,v in census.iteritems()}
for python 2.6:
newDict = dict((k,v /sum) for (k,v) in census.iteritems())
The following Python code will modify the dictionary's keys to float values.
def turnIntoFractions(mydict):
total = sum(mydict.values())
for key in mydict:
mydict[key] = float(mydict[key]) / total

Categories