How to get a particular key from dictionary in python?
I have a dictionary as :
dict = {'redorange':'1', 'blackhawak':'2', 'garlicbread':'3'}
I want to get value of that key which contains garlic in its key name.
How I can achieve it?
Let's call your dictionary d:
print [v for k,v in d.iteritems() if 'garlic' in k]
prints a list of all corresponding values:
['3']
If you know you want a single value:
print next(v for k,v in d.iteritems() if 'garlic' in k)
prints
'3'
This raises StopIterationError if no such key/value is found. Add the default value:
print next((v for k,v in d.iteritems() if 'garlic' in k), None)
to get None if such a key is not found (or use another default value).
Related
I have a dict as below
{"low":[18,12,9],"medium":[6,3],"high":[2,1],"final":[0]}
and I want to search for a number in this dict and get its respective 'key'
Eg: for 12, i need to return 'low'. slly for 2, return 'high'
You can use a dictionary comprehension for this.
dict = {"low":[18,12,9],"medium":[6,3],"high":[2,1],"final":[0]}
key = {k:v for k, v in dict.items() if 12 in v}
Output
In[1]: key.popitem()[0]
Out[1] : 12
This is a job for next.
my_d = {"low":[18,12,9],"medium":[6,3],"high":[2,1],"final":[0]}
target = 12
res = next((k for k, v in my_d.items() if target in v), 'N\A')
print(res) # low
Note that if your target value exists in more than one keys, this code will return one of them at random1. If that might by the case and depending on the problem you are working on it may be wiser to get all matching keys instead. To do that, use:
res = [k for k, v in my_d.items() if target in v]
1Actually more like in an uncontrolled fashion.
def getKey(number):
for key, value in d.iteritems():
if number in value:
return key
dict = {"low":[18,12,9],"medium":[6,3],"high":[2,1],"final":[0]}
def search_key(val):
for key, value in dict.iteritems():
for i in value:
if i == val:
print "the key is:"+key
return key
#pass any value for which you want to get the key
search_key(9)
I have a dictionary where each key has several lists of data as its values like this
myDict = {'data1' : ['data_d','dataD']['data_e','dataE']['data_f','dataF']}
I want to be able to input one of the values in the list and then be given the key. This is so I can get the other value in the list now that I have the key.
I've tried
dataKey = (list(myDict.keys())[list(myDict.values()).index(dataD)])
but that didn't work
I've also tried
for k, v in myDict.items():
if 'dataD' in v:
print k
but that didn't work as well.
Side question, in the questions that I've looked through, I see people using the variable k and v a lot even without the OP mentioning them, so I am wondering if k and v are already set variable in dictionaries?
Your second attempt was almost right, but a nested for loop is needed to traverse the list-of-lists:
myDict = {'data1' : [['data_d','dataD'], ['data_e','dataE'], ['data_f','dataF']]}
for key, value in myDict.items():
for sublist in value:
if 'dataD' in sublist:
print(key) # -> data1
Using variables named k, and v with dictionaries is purely optional and aren't special properties—other than being very short abbreviations for "key" and "value".
Note that if only one match is ever expected to occur, the code could be made more efficient by stopping the search after one is found. Here's one way of doing that:
target = 'dataD'
try:
for key, value in myDict.items():
for sublist in value:
if target in sublist:
print(key) # -> data1
raise StopIteration # found, so quit searching
except StopIteration:
pass # found
else:
print('{} not found'.format(target))
if they are all going to be lists then you can do something like this (if i am understanding correctly)
myDict = {
'data1': [['data_d','dataD'], ['data_e','dataE'], ['data_f','dataF']],
}
def find(dic, item):
for k, v in dic.items():
for ls in v:
if item in ls:
return k
return False
print(find(myDict, "data_d"))
# OUT [data1]
I have a dict like this:
d = {'first':'', 'second':'', 'third':'value', 'fourth':''}
and I want to find first non-empty value (and it's name, in this example 'third'). There may be more than one non-empty value, but I only want the first one I find.
How can I do this?
Use an OrderedDict which preserves the order of elements. Then loop over them and find the first that isn't empty:
from collections import OrderedDict
d = OrderedDict()
# fill d
for key, value in d.items():
if value:
print(key, " is not empty!")
You could use next (dictionaries are unordered - this somewhat changed in Python 3.6 but that's only an implementation detail currently) to get one "not-empty" key-value pair:
>>> next((k, v) for k, v in d.items() if v)
('third', 'value')
Like this?
def none_empty_finder(dict):
for e in dict:
if dict[e] != '':
return [e,dict[e]]
d = {'first':'', 'second':'', 'third':'value', 'fourth':''}
for k, v in d.items():
if v!='':
return k, v
Edit 1
from the comment if the value is None or '' we better use if v: instead of if v!=''. if v!='' only check the '' and skip others
You can find empty elements and make a list of them:
non_empty_list = [(k,v) for k,v in a.items() if v]
By using list comprehension, you can list all the non-empty values and then fetch the 0th value:
[val for key, val in d.items() if val][0]
I have a dictionary, i need to sort it on the descending order of the MI Value.And print the contents in dict one by one in descending order along with 'hi'
My coding:
d = dict()
for item in a:
specificy = c[item]
MI1= specificx/float(specificy)
MI2= MI1*specificx
M13= specificx*specificy
MI = MI1* math.log(MI1/float(MI2))
d[x + ' ' + item] = MI
print d
for k,v in d:
print k + v + 'hi'
This should do:
import operator
for k in sorted(d.items(), key=operator.itemgetter(1), reverse=True):
print(k + d[k] + 'hi')
It works by getting the items of the dictionary, sorting them by the values, reversed, then printing that.
See also: https://stackoverflow.com/a/613218/565635
To sort using key change index of x to 0
for k,v in sorted(d.items(), key=lambda x: x[0], reverse=False):
print k + v + 'hi'
To sort using value change index of x to 1
for k,v in sorted(d.items(), key=lambda x: x[1], reverse=False):
print k + v + 'hi'
To sort a dictionary on the item value you can use
sorted(d, key=d.__getitem__)
In your case the code becomes
for k in sorted(d, key=d.__getitem__, reverse=True):
print(k + d[k] + "hi")
Explanation
When in Python you write
d[k]
what is evaluated is
d.__getitem__(k)
so d.__getitem__ when d is a dictionary is a function that given a key returns the value associated to that key in the dictionary.
sorted instead is a predefined function that returns a sorted version of a sequence and accepts an optional parameter (named somewhat unfortunately key, but note that key has no relation to dictionaries here). This parameter can be used to determine on what the ordering comparison should be done; sorted also supports another optional parameter reversed where you can determine if ascendant or descendant sorting is required.
Finally when a dictionary is used as a sequence (for example passing it to sorted or iterating over it in a for) what you obtain are the keys of the dictionary.
This for example implies that sorted(d, key=d.__getitem__) returns the keys of the dictionary sorted according the value.
I worked to access the item in ordered dictionary. d is the ordered dictionary:
print d.items()
Here the output is a pair. I want to access the key and value in this pair.
You can unpack the key, value (a tuple) as below:
for key, value in d.items():
print (key)
print (value)
This works both on python 2 and 3.
From docs:
Return a new view of the dictionary’s items ((key, value)
pairs).
Each "pair" in d.items() is a tuple (ordered, immutable sequence) (key, value). You can "unpack" the values in each tuple into separate names, for example in a for loop:
for key, value in d.items():