Need solution For Dictionary comprehension - python

This is the input:
d={"mango":50,"apple":100,"banana":70} # this is the input
This should be the output:
{"mango":35,"apple":70,"banana":49}
I tried this:
f = {i:int(i*0.7) for i in d}
How do I do this using dictionary compression only?

Try this
f = { k: int(v * 0.7) for k, v in d.items() }

Related

Iterating through a dictionary to get next values from previous values

I have this sample dataset
{'data1':200, 'data2':500}
I want to iterate this data in a range of 25, such that each iteration would give me the previous value * (1+0.05) within the iteration.
In this case the output of range of 2 would look like this:
{'data1':[200,210], 'data2':[500, 525]}
Anyone has an idea of how to go about this?
You could use a dictionary comprehension like this:
R = 25
d = {'data1': 200, 'data2': 500}
e = {k: [v * 1.05 ** i for i in range(R)] for k, v in d.items()}
print(e)
Output:
{'data1': [200.0, 210.0, 220.5, 231.52500000000003, 243.10125000000005, 255.25631250000006, 268.01912812500007, 281.4200845312501, 295.4910887578126, 310.26564319570326, 325.7789253554884, 342.0678716232628, 359.171265204426, 377.12982846464735, 395.98631988787974, 415.78563588227377, 436.5749176763874, 458.40366356020684, 481.3238467382171, 505.3900390751281, 530.6595410288844, 557.1925180803287, 585.0521439843452, 614.3047511835624, 645.0199887427406], 'data2': [500.0, 525.0, 551.25, 578.8125000000001, 607.7531250000001, 638.1407812500001, 670.0478203125002, 703.5502113281252, 738.7277218945316, 775.6641079892581, 814.447313388721, 855.1696790581572, 897.9281630110651, 942.8245711616183, 989.9657997196994, 1039.4640897056843, 1091.4372941909685, 1146.009158900517, 1203.309616845543, 1263.4750976878202, 1326.6488525722111, 1392.9812952008217, 1462.630359960863, 1535.761877958906, 1612.5499718568515]}
your can create a recursive function and a dictionnary comprehension which is faster than a loop:
d = {'data1':200, 'data2':500}
def g(value, n_range, factor):
if n_range <= 1:
return [value]
else:
return [value] + g(value * factor, n_range-1, factor)
def fct(data, n_range):
return {
k: g(v, n_range, factor=1.05)
for k, v in data.items()
}
fct(d, 2)
instead of g() you can also use a list comprehension such as:
def fct(data, n_range):
return {
k: [v*(1.05)**i for i in range(n_range)]
for k, v in data.items()
}
fct(d, 2)
dict = {'data1':200, 'data2':500}
e= {}
for key, value in dict.items():
v = value
tab = []
for i in range(25):
tab.append(v*(1.05)**i)
e[(key)]=tab
print(e)
OUTPUT :
{'data1': [200.0, 210.0, 220.5, 231.52500000000003, 243.10125000000005, 255.25631250000006, 268.01912812500007, 281.4200845312501, 295.4910887578126, 310.26564319570326, 325.7789253554884, 342.0678716232628, 359.171265204426, 377.12982846464735, 395.98631988787974, 415.78563588227377, 436.5749176763874, 458.40366356020684, 481.3238467382171, 505.3900390751281, 530.6595410288844, 557.1925180803287, 585.0521439843452, 614.3047511835624, 645.0199887427406], 'data2': [500.0, 525.0, 551.25, 578.8125000000001, 607.7531250000001, 638.1407812500001, 670.0478203125002, 703.5502113281252, 738.7277218945316, 775.6641079892581, 814.447313388721, 855.1696790581572, 897.9281630110651, 942.8245711616183, 989.9657997196994, 1039.4640897056843, 1091.4372941909685, 1146.009158900517, 1203.309616845543, 1263.4750976878202, 1326.6488525722111, 1392.9812952008217, 1462.630359960863, 1535.761877958906, 1612.5499718568515]}

Create a new dictionary from 2 existing dictionory (1 nested dictionory , 1 dictionory of lists) python

I have two dictionaries K and L. K is a Dictionary of lists and L is a nested dictionary
K={
'k1':[1,3,2],
'k2':[3,4,5],
'k3':[9,10,11]
}
L = {
'l1':{'a':'1','b':'1','c':'2'},
'l2':{'a':'1','b':'3','c':'2'},
'l3':{'a':'1','b':'2','c':'2'},
'l4':{'a':'1','b':'4','c':'2'}
}
What I need:
I want to create a new dictionary of lists based on the below condition.
I need to check if b values of L are present in the K dictionary of the list or not.
If present I need to return a new dictionary with Key of K
dictionary and Key of L dictionary.
For the above example, I need to return something like this
M = {'k1':[l1,l3,l2]
'k2':[l2,l4]
}
Here is the code that I have tried:
M= {}
for k, v in K.items():
temp = []
for i in v:
if L[i]['b'] in K[k]:
temp.append(i)
M[k] = temp
print(M)
Here is your solution:
new_dict, M = dict(), dict()
for key, val in L.items():
new_dict[val['b']] = key
for key, val in K.items():
for x in val:
if str(x) in new_dict:
tmp = new_dict[str(x)]
lst = M[key] if key in M else list()
lst.append(tmp)
M[key] = lst
print(M)
For the following K, L:
K = {
'k1':[1,3,2],
'k2':[3,4,5],
'k3':[9,10,11]
}
L = {
'l1':{'a':'1','b':'1','c':'2'},
'l2':{'a':'1','b':'3','c':'2'},
'l3':{'a':'1','b':'2','c':'2'},
'l4':{'a':'1','b':'4','c':'2'}
}
Output M:
M = {
'k2': ['l2', 'l4'],
'k1': ['l1', 'l2', 'l3']
}
[ Considered b values of L has a unique value, if not then you have to store it as a list in the new_dict dictionary.]
You were looking up the wrong thing in L here L[I]. I would do this by creating a lookup intially from L, that way you don't have to loop through L for every key in K. From there you can go through K once, looking up the items from the lookup.
Using defaultdict also allows you to handle the case where L has b values that are the same
from collections import defaultdict
b_val_to_l = defaultdict(set)
for lkey, ldict in L.items():
# For each ldict, extract the 'b' value, convert to an int and add the
# l key to the set of l values for the corresponding b value
b_val_to_l[int(ldict['b'])].add(lkey)
print(b_val_to_l)
M = defaultdict(list)
for k, v in K.items():
for i in v:
# For each value in the k, get the set of corresponding l values
b_set = b_val_to_l.get(i, set())
# Add to the output dict
M[k].extend(list(b_set))
print(M)
Just do this:
Mtemp = { k: [l for l in L
if int(L[l]['b']) in K[k]
] for k in K }
# Mtemp can have None values, so let's remove them...
M = { k: l for k, l in Mtemp.items() if len(l) > 0 }
Output:
{'k1': ['l1', 'l2', 'l3'], 'k2': ['l2', 'l4']}

compare values from a list with values from a dictionary

I have a dictionary contains lists of values and a list:
dict={'first':45, 'second':30, 'third':56}
list= [30,45]
I want to compare the value in the dictionary with the list and a match to add to a new dictionary after that, remove from the old dict all the values that are in the new dict: I'm doing something like this:
def get_sessions(self, talks):
result_sessions = {}
for k, v in self.sessions.items():
for i in talks:
if v == i:
result_sessions[k] = v
for k, v in result_sessions.items():
del self.sessions[k]
return result_sessions
Maybe you know a more elegant solution? any help?
This is one approach.
Ex:
d ={'first':45, 'second':30, 'third':56}
lst = [30,45]
result_sessions = {k: v for k, v in d.items() if v in lst}
d = { k : d[k] for k in set(d) - set(result_sessions) }
print(result_sessions)
print(d)
Output:
{'second': 30, 'first': 45}
{'third': 56}

Update dictionary and append if key exists

I've got a list of dictionarys.
list_of_dicts = [{ a: 1, b:f, c:3}, {a: y, b:q, c:z, d: 1}, ... ]
Now i want to create a new dictionary which looks like:
newDict = { a: [1,y], b: [f,q], c: [3,z], d:[1]}
I know i could could make a double for loop, but that is rather slow since I'm dealing with large objects (mostly NumPy arrays) in the dictionaries.
newDict = {}
for l in list_of_dicts:
for k, v in l.items():
if k in newDict:
newDict.append(v)
else:
newDict[k] = [v]
How to do this faster?
Using a collections.defaultdict() will improve the performance:
result = defaultdict(list)
for d in list_of_dicts:
for k, v in d.items():
result[k].append(v)
This is the fastest you can do this. You can replace the if with newdict.setdefault(k, []).append(v) to simplify it, but there is nothing you can do that will be faster than two loops.

Sum up values from a dictionary (the Python way)

Given the following dictionary, let's call it mydict
{'Plekhg2': {'Bcells': '233.55', 'DendriticCells': '190.12'},
'Barxxxx': {'Bcells': '132.11', 'DendriticCells': '92.01'}, }
I want to sum up values for each key from inner dictionary, resulting in:
{'Plekhg2': 423.67, # 233.55 + 190.12
'Barxxxx': 224.12} # 132.11 + 92.01
How can I achieve that with Python idiom?
With a dict comprehension, using sum() to sum the nested dictionary values; Python 2.6 or before would use dict() and a generator expression:
# Python 2.7
{k: sum(float(f) for f in v.itervalues()) for k, v in mydict.iteritems()}
# Python 3.x
{k: sum(map(float, v.values())) for k, v in mydict.items()}
# Python 2.6 and before
dict((k, sum(float(f) for f in v.values())) for k, v in mydict.iteritems())
You may want to store float values to begin with though.
Demo:
>>> mydict ={'Plekhg2': {'Bcells': '233.55', 'DendriticCells': '190.12'},
... 'Barxxxx': {'Bcells': '132.11', 'DendriticCells': '92.01'}, }
>>> {k: sum(float(f) for f in v.itervalues()) for k, v in mydict.iteritems()}
{'Plekhg2': 423.67, 'Barxxxx': 224.12}
Use a dict comprehension and sum, since the values are strings you'll have to convert them to floats first using float.
>>> {k:sum(float(x) for x in v.itervalues()) for k, v in d.iteritems()}
{'Plekhg2': 423.67, 'Barxxxx': 224.12}
For Python 3 use .items() and .values() instead of the .iter(values|items).
Just for completion in Python 3:
In [134]:
{k:sum(float(x) for x in v.values()) for k, v in my_dict.items()}
Out[134]:
{'Barxxxx': 224.12, 'Plekhg2': 423.67}

Categories

Resources