Dictionary get value without knowing the key - python

In python if I have a dictionary which has a single key value pair and if I don't know what the key might be, how can I get the value?
(and if I have a dict with more than 1 key, value pair, how can I return any one of the values without knowing any of the keys?)

You just have to use dict.values().
This will return a list containing all the values of your dictionary, without having to specify any key.
You may also be interested in:
.keys(): return a list containing the keys
.items(): return a list of tuples (key, value)
Note that in Python 3, returned value is not actually proper list but view object.

Other solution, using popitem and unpacking:
d = {"unknow_key": "value"}
_, v = d.popitem()
assert v == "value"

Further to Delgan's excellent answer, here is an example for Python 3 that demonstrates how to use the view object:
In Python 3 you can print the values, without knowing/using the keys, thus:
for item in my_dict:
print( list( item.values() )[0] )
Example:
cars = {'Toyota':['Camry','Turcel','Tundra','Tacoma'],'Ford':['Mustang','Capri','OrRepairDaily'],'Chev':['Malibu','Corvette']}
vals = list( cars.values() )
keyz = list( cars.keys() )
cnt = 0
for val in vals:
print('[_' + keyz[cnt] + '_]')
if len(val)>1:
for part in val:
print(part)
else:
print( val[0] )
cnt += 1
OUTPUT:
[_Toyota_]
Camry
Turcel
Tundra
Tacoma
[_Ford_]
Mustang
Capri
OrRepairDaily
[_Chev_]
Malibu
Corvette
That Py3 docs reference again:
https://docs.python.org/3.5/library/stdtypes.html#dict-views

Two more ways:
>>> d = {'k': 'v'}
>>> next(iter(d.values()))
'v'
>>> v, = d.values()
>>> v
'v'

One more way: looping with for/in through a dictionary we get the key(s) of the key-value pair(s), and with that, we get the value of the value.
>>>my_dict = {'a' : 25}
>>>for key in my_dict:
print(my_dict[key])
25
>>> my_other_dict = {'b': 33, 'c': 44}
>>> for key in my_other_dict:
print(my_other_dict[key])
33
44

Related

A python program to filter dictionary

Write a python program to filter a dictionary based on values that are the multiples of 6
NOTE:
Take keys as strings and values as integers.
Constraints:
1<=number of key value pairs<=10
Sample test case: keys : a,b,c,d,e,f values:1,2,3,4,5,6 {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6} {'f':6}
You can use a dict comprehension.
d = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
res = {k:v for k,v in d.items() if v % 6 == 0}
print(res)
old_dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
#or this it will work totally perfect
#old_dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13}
print (f"Original dictionary is : {old_dict}")
print()
new_dict = {key:value for (key, value) in old_dict.items() if value % 6 == 0}
print(f"New dictionary with multiple of 6 is : {new_dict}")

How to access key by value in a dictionary?

I have a dict that looks like the following:
d = {"employee": ['PER', 'ORG']}
I have a list of tags ('PER', 'ORG',....) that is extracted from the specific entity list.
for t in entities_with_tag: # it includes words with a tag such as: [PER(['Bill']), ORG(['Microsoft']),
f = t.tag # this extract only tag like: {'PER, ORG'}
s =str(f)
q.add(s)
Now I want if {'PER, ORG'} in q, and it matched with d.values(), it should give me the keys of {'PER, ORG'} which is 'employee'. I try it this but does not work.
for x in q:
if str(x) in str(d.values()):
print(d.keys()) # this print all the keys of dict.
If I understand correctly you should loop he dictionary instead of the tag list. You can check if the dictionary tags are in the list using sets.
d = {"employee": ['PER', 'ORG'],
"located": ["ORG", "LOC"]}
q = ["PER", "ORG", "DOG", "CAT"]
qset = set(q)
for key, value in d.items():
if set(value).issubset(qset):
print (key)
Output:
employee
You mean with... nothing?
for x in q:
if str(x) in d.values():
print(d.keys())
What you can do is to switch keys and values in the dict and then access by key.
tags = ('PER', 'ORG')
data = dict((val, key) for key, val in d.items())
print(data[tags])
Just be careful to convert the lists in tuples, since lists are not hashable.
Another solution would be to extract both key and value in a loop. But that's absolutely NOT efficient at all.
for x in q:
if str(x) in str(d.values()):
for key, val in d.items():
if val == x:
print(key) # this print all the keys of dict.
What you can do is make two lists. One which contains the keys and one which contains the values. Then for the index of the required value in the list with values you can call the key from the list of keys.
d = {"employee": ['PER', 'ORG']}
key_list = list(d.keys())
val_list = list(d.values())
print(key_list[val_list.index(['PER','ORG'])
Refer: https://www.geeksforgeeks.org/python-get-key-from-value-in-dictionary/

Extract all single {key:value} pairs from dictionary

I have a dictionary which maps some keys to 1 or more values.
In order to map to more than 1 value, I'm mapping each individual key to a list. How can I get the number of the single pairs? Is there a quick pythonic way to do this?
My dict looks something like this:
>>print dict
{'key1':['value11',value12, ...], 'key2': ['value21'], 'key3':['value31', 'value32']}
So in the above example, I would expect my output to be 1
With d being the dictionary:
sum(len(v) == 1 for v in d.values())
Or:
map(len, d.values()).count(1)
(The latter requires list around the map if you're using Python 3.)
You could try something like
len([_ for v in d.values() if len(v) == 1])
where d is the name of your dictionary (you should avoid using identifiers such as dict, incidentally).
Depending on your interpreter version, you might need to use itervalues instead of values.
You can use #MosesKoledoye's solution for the short (and probably a tiny bit faster) solution, or this naive version:
print(len([value for value in d.values()
if hasattr(value, '__len__') and len(value) == 1]))
Iterate through values in dictionary and count:
count = 0
for value in dic.values():
if len(value) == 1:
count += 1
print count
You could just filter your dictionary out like this:
data = {
'key1': ['value11', 'value12'],
'key2': ['value21'],
'key3': ['value31', 'value32']
}
result = filter(lambda (k, v): len(v) == 1, data.iteritems())
print result, "=>", len(result)

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

Deleting from dict if found in new list in Python

Say I have a dictionary with whatever number of values.
And then I create a list.
If any of the values of the list are found in the dictionary, regardless of whether or not it is a key or an index how do I delete the full value?
E.g:
dictionary = {1:3,4:5}
list = [1]
...
dictionary = {4:5}
How do I do this without creating a new dictionary?
for key, value in list(dic.items()):
if key in lst or value in lst:
del dic[key]
No need to create a separate list or dictionary.
I interpreted "whether or not it is a key or an index" to mean "whether or not it is a key or a value [in the dictionary]"
it's a bit complicated because of your "values" requirement:
>>> dic = {1: 3, 4: 5}
>>> ls = set([1])
>>> dels = []
>>> for k, v in dic.items():
if k in ls or v in ls:
dels.append(k)
>>> for i in dels:
del dic[i]
>>> dic
{4: 5}
A one liner to do this would be :
[dictionary.pop(x) for x in list if x in dictionary.keys()]
dictionary = {1:3,4:5}
list = [1]
for key in list:
if key in dictionary:
del dictionary[key]
>>> dictionary = {1:3,4:5}
>>> list = [1]
>>> for x in list:
... if x in dictionary:
... del(dictionary[x])
...
>>> dictionary
{4: 5}
def remKeys(dictionary, list):
for i in list:
if i in dictionary.keys():
dictionary.pop(i)
return dictionary
I would do something like:
for i in list:
if dictionary.has_key(i):
del dictionary[i]
But I am sure there are better ways.
A few more testcases to define how I interpret your question:
#!/usr/bin/env python
def test(beforedic,afterdic,removelist):
d = beforedic
l = removelist
for i in l:
for (k,v) in list(d.items()):
if k == i or v == i:
del d[k]
assert d == afterdic,"d is "+str(d)
test({1:3,4:5},{4:5},[1])
test({1:3,4:5},{4:5},[3])
test({1:3,4:5},{1:3,4:5},[9])
test({1:3,4:5},{4:5},[1,3])
If the dictionary is small enough, it's easier to just make a new one. Removing all items whose key is in the set s from the dictionary d:
d = dict((k, v) for (k, v) in d.items() if not k in s)
Removing all items whose key or value is in the set s from the dictionary d:
d = dict((k, v) for (k, v) in d.items() if not k in s and not v in s)

Categories