i'm trying to find a element in a list and return the the key who has that list.
Example:
mydict = {'hi':[1,2], 'hello':[3,4]}
print(find(1))
return 'hi
Is there any simple way to do it?
This function will return all the keys that contain the given value as a list.
def find(to_find, inp_dct):
return [i for i in inp_dct if to_find in inp_dct[i]]
You can simply loop through your dictionary as key,value pairs and your search value is in values list, it will return the value.
Code:
mydict = {'hi':[1,2], 'hello':[3,4]}
def find(item):
for key, value in mydict.items():
if item in value:
return key
print(find(1))
Output: hi
for k in mydict:
if val in mydict[k]:
print(k)
Where val is the value you want to find.
Related
Hey everyone trying to multiply the keys * values within a python dictionary.
I have the following code:
dic = {'coca-cola':3, 'fanta':2}
def inventory(data):
lis = []
lis = [key * val for key, val in data.items()]
return lis
inventory(dic)
However my output is
['coca-colacoca-colacoca-cola', 'fantafanta']
and I would like to get
['coca-cola', 'coca-cola', 'coca-cola', 'fanta', 'fanta']
Please Help
because multiplication of string doesnt return what you excpacted, it multiply the string into a one longer string, you better use the piece of code #deadshot suggested:
def inventory(data):
return [key for key, val in data.items() for i in range(val)]
the output would be as you expacted...
Use following code.
dic = {'coca-cola':3, 'fanta':2}
def inventory(data):
lis = []
for key, val in data.items():
for item in range(0,val):
lis.append(key)
return lis
Multiplying a str by an int (as in your original attempt) will simply return a str of repetitions of the original str. e.g. 3 * 'hi' = 'hihihi'.
Instead you want to return a list where each key from your dict is stored val number of times for each key:value pair in your dict. The below list comprehension does this.
Solution
def inventory(data):
return [key for key, val in data.items() for i in range(val)]
dic = {'coca-cola':3, 'fanta':2}
print(inventory(dic))
Output
['coca-cola', 'coca-cola', 'coca-cola', 'fanta', 'fanta']
Hello I found this if you want solve your problem:
dic = {'coca-cola':3, 'fanta':2}
def inventory(data):
lis = []
lis = [[key]* val for key, val in data.items()]
return lis
print (inventory(dic))
and you get this :
[['coca-cola', 'coca-cola', 'coca-cola'], ['fanta', 'fanta']]
Let me give you an example for this. I have a dictionary
word = 'mango'
my_dict = {'A':['apple','banana','pear'],
'B':['mango','carrot','guava'],
'C':['orange','lemon','ginger']}
I want to be able to return 'B' as the answer by iterating through all the list/value elements . How could I do this? functions and comprehensions are both acceptable. Please help me out.
Something like:
word = 'mango'
my_dict = {'A':['apple','banana','pear'],
'B':['mango','carrot','guava'],
'C':['orange','lemon','ginger']}
def search_value():
for key, _list in my_dict.items():
if word in _list:
return key
print(search_value()) # B
I am trying to find a value inside a list that is inside a dictionary whitout using the key
and the purpose is so that i cant add the same name to the dictionary.
The dictionary looks something like this:
Dict={'1_number': ['1_name'], '2_number': ['2_name', '3_name']}
so i am trying to check if 3_name exists inside the dictionary.
Also trying to display 2_number by searching for it with 2_name, that is displaying the key by finding it with one of its values.
You can actually combine list comprehension to iterate over the values of a dictionary with any for short circuit evaluation to search an item to get the desired result
>>> any('3_name' in item for item in Dict.values())
True
alternatively, if you are interested to return all instances of dictionaries which have the concerned item, just ensure that the condition to check the item in its value is within the if statement and key value pair is returned as part of the filter List Comprehension
>>> [(k, v) for k, v in Dict.items() if '3_name' in v]
[('2_number', ['2_name', '3_name'])]
Finally, if you are sure there is one and only one item, or you would like to return the first hit, use a generator with a next
>>> next((k, v) for k, v in Dict.items() if '3_name' in v)
('2_number', ['2_name', '3_name'])
You can iterate of the values of a dictionary and check for the pressence of the wanted list value:
>>> def find_in_dict(d, name):
>>> for k,vals in d.iteritems():
>>> if name in vals:
>>> return k
>>> else:
>>> return False
>>> find_in_dict(d,'3_name')
'2_number'
>>> find_in_dict(d,'4_name')
False
You can use a list comprehension to search the values of the dictionary, then return a tuple of (key, value) if you find the key corresponding to the value you are searching for.
d = {'1_number': ['1_name'], '2_number': ['2_name', '3_name']}
search = '3_name'
>>> [(key, value) for key, value in d.items() if search in value]
[('2_number', ['2_name', '3_name'])]
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
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