Remove empty values from dictionary [duplicate] - python

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}

Related

Is there a more efficient way to delete elements from a dictionary? [duplicate]

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}

using dictionary comprehension for a new dict [duplicate]

This question already has answers here:
Create a dictionary with comprehension
(17 answers)
Closed 2 years ago.
Been informed this has been answered - apoligies
Thank you!
Since you wanted a function to perform this:
def newprice(d):
return {"all" + key: value * 5 for key, value in d.items()}
# To be used as :
dict1 = {'apple':5, 'banana':4}
print(newprice(dict1))
In dictionary comprehension you can do whatever you want to keys and values:
def newprice(d):
return {f'all{k}': v * 5 for k, v in d.items()}
Here you go -
dict1 = {'apple':5, 'banana':4}
dict2 = {('all'+ k): 5*dict1[k] for k in dict1 }
print(dict2)

accessing nested dict from list of keys [duplicate]

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

Enumerating through a dictionary in Python [duplicate]

This question already has an answer here:
Zip list of tuples with flat list
(1 answer)
Closed 6 years ago.
I am trying to enumerate through a dictionary like this but it does not work. What's the simplest way to iterate through a dictionary in python while enumerating each entry?
for i, k, v in enumerate(my_dict.iteritems()):
print i, k, v
You just need to add parenthesis around (k, v) tuple:
>>> d = {1: 'foo', 2: 'bar'}
>>> for i, (k, v) in enumerate(d.iteritems()):
... print i, k, v
...
0 1 foo
1 2 bar

build a dictionary for find key by value [duplicate]

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)

Categories