This question already has answers here:
filter items in a python dictionary where keys contain a specific string
(6 answers)
Closed 8 months ago.
d = {'a1':1, 'a2':2,'a3':3,'a4':1,'a5':1,'b':2, 'c':3}
for k, v in d.copy().items():
if 'a' in k:
del d[k]
print(d)
I want to delete elements if the key or value meets a certain requirement, as above, in which the keys containing 'a' will be deleted.
In particular, can I somehow not use the copy() function to do the same thing?
EDIT: Based on suggestion, I adopted this way:
for k in list(d):
if 'a' in k:
del d[k]
Create a new dictionary without the key you want to filter
d = {'a1':1, 'a2':2,'a3':3,'a4':1,'a5':1,'b':2, 'c':3}
filtered_d = {k: v for k,v in d.items() if 'a' not in k}
This question already has answers here:
How can I calculate average of different values in each key of python dictionary?
(3 answers)
Closed 2 years ago.
I have an existing dictionary called StudentGrad that has the following data type:
('Aditya','male','senior'):[0.83,0.87,0.82,0.83],
('Varun','male','senior'):[0.76,0.86,0.88,0.79],
('Shantanu','male','senior'):[0.79,0.81,0.78,0.78],
I want to create a new dictionary called studentAvg that has the same keys, but returns an average grade for the values:
('Aditya','male','senior'):[0.84],
('Varun','male','senior'):[0.82],
('Shantanu','male','senior'):[0.79],
Any help would be appreciated....
Thanks!
Try to do this:
x = {('Aditya','male','senior'):[0.83,0.87,0.82,0.83],
('Varun','male','senior'):[0.76,0.86,0.88,0.79],
('Shantanu','male','senior'):[0.79,0.81,0.78,0.78]}
def average(data):
sum = 0
for elem in data:
sum+=elem
result = sum/len(data)
return result
y = {}
for elem in x:
y[elem] = average(x[elem])
You can use a dict comprehension and a custom function for averaging :
d1 = {('Aditya','male','senior'):[0.83,0.87,0.82,0.83],
('Varun','male','senior'):[0.76,0.86,0.88,0.79],
('Shantanu','male','senior'):[0.79,0.81,0.78,0.78],
}
def average(list_values):
"let's assume you want an arithmetic mean"
return sum(list_values) / len(list_values)
d2 = {k:average(val) for k, val in d1.items()}
And if you really want a list of the average (as stated in the question) :
d2 = {k:[average(val)] for k, val in d1.items()}
Try this:
studentAvg = {
('Aditya','male','senior'):sum(studendGrad["('Aditya','male','senior')"])/len(studendGrad["('Aditya','male','senior')"]),
('Varun','male','senior'):sum(studentGrad["(Varun','male','senior')"])/len(studentGrad["('Varun','male','senior')"]),
('Shantanu','male','senior'):sum(studentGrad["('Shantanu','male','senior')"]/len(studentGrad["('Shantanu','male','senior')"])
}
This question already has answers here:
Iterating over dictionaries using 'for' loops
(15 answers)
Python - Remove dicts with empty values from list of dictionaries
(1 answer)
Closed 2 years ago.
I have a question regarding a dictionary in python and empty values.
If I had the following dictionary
my_dict={'a':[],
'b':[1],
'c':[],
'd':[]
}
How I could remove empty values [] and appending the keys in an empty list?
my_dict={
'b':[1],
}
and empty_list=['a','c','d'].
With a list I would do as follows (but there are several ways to do the same):
my_dict = list(filter(None, my_dict))
But I have realised I do not know how to do the same in a dictionary.
You can use a dict comprehension to remove empty values:
new_dict = {k: v for k, v in my_dict.items() if v}
Then you can use set difference to get the removed keys:
removed_keys = my_dict.keys() - new_dict.keys()
Just do two explicit iterations for a clean solution -- first calculate the empty_list, then filter down my_dict:
empty_list = [k for k, v in my_dict.items() if len(v) == 0]
my_dict = {k: v for k, v in my_dict.items() if len(v) != 0}
This question already has answers here:
Access nested dictionary items via a list of keys?
(20 answers)
Closed 3 years ago.
I have a a nested dict object with N layers:
d={'l0':{'l1':{'l2':...}}}
in addition, I have a list of all the dict keys:
k=['l0','l1','l2',...]
how can I access the element defined by the list,for an arbitrary list, that is:
d[k[0]][k[1]][k[2]].... = X
(I would like a function that return the reference to the data...)
One approach is the following:
def resolve_value(obj, keys):
for key in keys:
obj = obj[key]
return obj
k = ['l0', 'l1', 'l2']
d = {'l0': {'l1': {'l2': 'hello'}}}
print(resolve_value(d, k))
Output
hello
You can go with the intuitive solution:
val = d
for key in k:
val = val[key]
# operations with val here
This question already has answers here:
Two way/reverse map [duplicate]
(15 answers)
Closed 10 years ago.
dictionary is usually good for find value by key,but find key by value is pretty slow
for k,v in dictionary.items():
if v = myValue:
return k
is there already a data structure that make both key->value and ke
You could try bidict:
>>> husbands2wives = bidict({'john': 'jackie'})
>>> husbands2wives['john'] # the forward mapping is just like with dict
'jackie'
>>> husbands2wives[:'jackie'] # use slice for the inverse mapping
'john'
Just create an inverted mapping:
from collections import defaultdict
inverted = defaultdict(list)
for k, v in dictionary.iteritems():
inverted[v].append(k)
Note that the above code handles duplicate values; inverted[v] returns a list of keys that hold that value.
If your values are also unique, a simple dict can be used instead of defaultdict:
inverted = { v: k for k, v in dictionary.iteritems() }
or, in python 3, where items() is a dictionary view:
inverted = { v: k for k, v in dictionary.items() }
Python 3:
revdict = {v:k for k,v in dictionary.items()}
(Python 2 use .iteritems() instead)