Python Dictionary Multiplying Keys * Values - python

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

Related

Find dictionary key using value from list

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.

I am trying to convert any dict to a list through a function, but it's not working and can't find out why

dict1 = {}
list1 = []
def convert_to_list(entry):
""" ... """
for k, v in dict1:
entry = (k, dict1[v])
new_list = list1.append(entry)
return new_list
convert_to_list({'a': 1})
Even when I define new_list globally it still doesn't work.
Can you please take a look and help me fix this?
There are multiple mistakes in the method that you have written:
you are passing entry as parameter to the method but you are trying to access elements in dict1 which is currently empty.
in for loop, you should use entry.items() instead of just dict1
append method does return a new list, it just adds elements to existing list.
so you should use new_list.append()
In [10]: def convert_to_list(entry):
...: new_list=[]
...: for k,v in entry.items():
...: print(k,v)
...: entry1 = (k,v)
...: new_list.append(entry1)
...: return new_list
...:
In [11]:
In [11]: convert_to_list({'a':1})
a 1
Out[11]: [('a', 1)]
You can convert a dict to a list of tuples like this:
def convert_to_list(entry):
""" ... """
return list(entry.items())
entry_list = convert_to_list({'a': 1})
I have no clue what you are doing:
def dicttolist(dictx):
return list(dictx.items())
This will turn any doct to what it seems that you are trying to do
dicttolist({'a':1})
>>> [('a',1)]
Because you're looping through dict1, not the argument. Also, you can't do
for k, v in entry:
Because then it's trying to unpack a tuple. You have to do
for k in entry:
And access elements of entry using .get(). This is working code for that function:
def convert_to_list(entry):
""" ... """
new_list = [] # Create a new list
for k in entry: # Loop through entry's keys
new_list.append((k, entry.get(k))) # append the key and value (the value has been found using .get())
return new_list # return the list

Return key of list value while searching for element in list Python

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

Python how to replace values in one list with values in a dictionary?

example:
my list is ['tree','world','tre','worl']
my dict is {'tre':'good','worl':nice}
my scripts:
def replace(list, dictionary):
for i in list:
for k in dictionary:
list = list.replace(k, dictionary[k])
return list
print replace(input_file,curaw_dict)
but every time I receive the result is like:
goode
niced
good
nice
how can I make it more accurate
make it like
tree
world
good
nice
Thanks alot
Lets make it a list comprehension instead.
replaced_list = [x if x not in my_dict else my_dict[x] for x in my_list]
I guess if you want a function you could do:
replace = lambda my_dict, my_list: [x if x not in my_dict else my_dict[x] for x in my_list]
or
def replace(my_list, my_dict):
return [x if x not in my_dict else my_dict[x] for x in my_list]
input_file = ['tree', 'world', 'tre', 'worl']
curaw_dict = {'tre':'good','worl':'nice'}
def replace(list, dictionary):
return [curaw_dict.get(item, item) for item in list]
print replace(input_file,curaw_dict)
>>> li=['tree', 'world', 'tre', 'worl']
>>> di={'tre':'good','worl':'nice'}
>>> print('\n'.join(di.get(e,e) for e in li))
tree
world
good
nice
def replace(list, dictionary):
for idx, val in enumerate(list):
if i in k:
list[idx] = dictionary[list[idx]]
return list
print replace(input_file,curaw_dict)
You don't need to iterate over a dictionary. Replace does partial replacements, but in will check if a key exists in a dictionary.
'key' in dictionary is the way to check if a key exists in a dict:
def replace(list, dictionary):
new_list = []
for i in list:
if i in dictionary:
new_list.append(dictionary[i])
else:
new_list.append(i)
return new_list
for k in dictionary: is not the correct way to iterate over the items in the dictionary. Instead, you should use enumerate to iterate over the items in the list and look them up in the dictionary:
def replace(lst, dictionary):
for k,v in enumerate(lst):
if v in dictionary:
lst[k] = dictionary[v]
return lst
For each item in the list, k is the index of the value and v is the value itself. You then check if the value is in the dictionary, and if it is, you replace the value in the list with the value in the dictionary.
You also should not name your variables list, since that is a reserved word in Python.
You can alternatively use a list comprehension:
def replace(lst, dictionary):
return [item if not item in dictionary else dictionary[item] for item in lst]

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