I currently have a program using the for loop down below however I don't want to use it because it slows the program down by a lot. Is there a better way to approach this?
for key, value in dict(dictionary_notes).items():
if 'XYZ' in value:
del dictionary_notes[key]
With the information given (which is almost none), the only way I can think of to improve this is through a dict comprehension
{k:v for k,v in d.items() if 'XYZ' not in v}
dictionary_notes = {'a': 'XYZ'}
{k:v for k, v in dict(dictionary_notes).items() if 'XYZ' not in v}
Returns: {}
Use comprehensions:
filtered = [(k, v) for (k, v) in dict(dictionary_notes).items() if 'XYZ' not in v]
EDIT
As someone mentioned below, above statement actually produces a list. To get back a dict, use this instead:
filtered = {k: v for (k, v) in dict(dictionary_notes).items() if 'XYZ' not in v}
I'm currently writing a function that takes a dictionary with immutable values and returns an inverted dictionary. So far, my code is getting extremely simple tests right, but it still has some kinks to work out
def dict_invert(d):
inv_map = {v: k for k, v in d.items()}
return inv_map
list1 = [1,2,3,4,5,6,7,8]
list2 = {[1]:3245,[2]:4356,[3]:6578}
d = {['a']:[],['b']:[]}
d['a'].append(list1)
d['b'].append(list2)
How do I fix my code so that it passes the test cases?
My only thoughts are to change list 2 to [1:32, 2:43, 3:54, 4:65]; however, I would still have a problem with having the "[]" in the right spot. I have no idea how to do that.
The trick is to realize that multiple keys can have the same values, so when inverting, you must make sure your values map to a list of keys.
from collections import defaultdict
def dict_invert(d):
inv_map = defaultdict(list)
for k, v in d.items():
inv_map[v].append(k)
return inv_map
EDIT:
Just adding a bit of more helpful info...
The defaultdict(list) makes the default value of the dict = list() when accessed via [] or get (when normally it would raise KeyError or return None respectively).
With that defaultdict in place, you can use a bit of logic to group keys together... here's an example to illustrate (from my comment above)
Original dict: K0 -> V0, K1 -> V0, K2 -> V0
Should invert to: V0 -> [K0, K1, K2]
EDIT 2:
Your tests seem to be forcing you into using a normal dict, in which case...
def dict_invert(d):
inv_map = {}
for k, v in d.items():
if v not in inv_map:
inv_map[v] = []
inv_map[v].append(k)
return inv_map
Python version 2.7
>>> json.loads('{"key":null,"key2":"yyy"}')
{u'key2': u'yyy', u'key': None}
The above is the default behaviour. What I want is the result to become:
{u'key2': u'yyy'}
Any suggestions? Thanks a lot!
You can filter the result after loading:
res = json.loads(json_value)
res = {k: v for k, v in res.iteritems() if v is not None}
Or you can do this in the object_hook callable:
def remove_nulls(d):
return {k: v for k, v in d.iteritems() if v is not None}
res = json.loads(json_value, object_hook=remove_nulls)
which will handle recursive dictionaries too.
For Python 3, use .items() instead of .iteritems() to efficiently enumerate the keys and values of the dictionary.
Demo:
>>> import json
>>> json_value = '{"key":null,"key2":"yyy"}'
>>> def remove_nulls(d):
... return {k: v for k, v in d.iteritems() if v is not None}
...
>>> json.loads(json_value, object_hook=remove_nulls)
{u'key2': u'yyy'}
>>> json_value = '{"key":null,"key2":"yyy", "key3":{"foo":null}}'
>>> json.loads(json_value, object_hook=remove_nulls)
{u'key3': {}, u'key2': u'yyy'}
I wrote the following solution before finding this question. Using object_hook is better, but in case you need to remove all nested elements of an already parsed JSON, you can use the following recursive function:
def remove_nulls (d):
if isinstance(d, dict):
for k, v in list(d.items()):
if v is None:
del d[k]
else:
remove_nulls(v)
if isinstance(d, list):
for v in d:
remove_nulls(v)
return d
Notice that it will change your existing dictionary.
I wasn't sure what the term is, but basically I have a word_set in the form of a defaultdict [(word, value), ...] that came from a function that parsed some raw data.
I have other functions: reduceVal(word_set, min_val), reduceWord(word_set, *args), etc that removes pairs that: have a value less than min_val, have their (word) in [args], respectively. They all pretty much follow the same structure, e.g.
def reduceVal(word_set, value):
"Returns word_set with (k, v) pairs where v > value)"
rtn_set = defaultdict()
for (k, v) in word_set.items():
if v > value:
rtn_set.update({k:v})
return rtn_set
I was wondering if there was a more concise, or pythonic, way of expressing this, without building a new rtn_set or maybe even defining an entire function
If you learn to use dict comprehensions you don't need to have separate functions for all of these different filters. For instance, reduceVal and reduceWord could be replaced with:
# Python 2.7+
{w: v for w, v in word_set.items() if v > value}
{w: v for w, v in word_set.items() if w in args}
# Python 2.6 and earlier
dict((w, v) for w, v in word_set.iteritems() if v > value)
dict((w, v) for w, v in word_set.iteritems() if w in args)
Use a dict-comprehension, defaultdict is not required here:
new_dict = {k:v for k, v in word_set.items() if v > value}
on py2.x you should use word_set.iteritems() as it returns an iterator.
I have a dict and would like to remove all the keys for which there are empty value strings.
metadata = {u'Composite:PreviewImage': u'(Binary data 101973 bytes)',
u'EXIF:CFAPattern2': u''}
What is the best way to do this?
Python 2.X
dict((k, v) for k, v in metadata.iteritems() if v)
Python 2.7 - 3.X
{k: v for k, v in metadata.items() if v}
Note that all of your keys have values. It's just that some of those values are the empty string. There's no such thing as a key in a dict without a value; if it didn't have a value, it wouldn't be in the dict.
It can get even shorter than BrenBarn's solution (and more readable I think)
{k: v for k, v in metadata.items() if v}
Tested with Python 2.7.3.
If you really need to modify the original dictionary:
empty_keys = [k for k,v in metadata.iteritems() if not v]
for k in empty_keys:
del metadata[k]
Note that we have to make a list of the empty keys because we can't modify a dictionary while iterating through it (as you may have noticed). This is less expensive (memory-wise) than creating a brand-new dictionary, though, unless there are a lot of entries with empty values.
If you want a full-featured, yet succinct approach to handling real-world data structures which are often nested, and can even contain cycles, I recommend looking at the remap utility from the boltons utility package.
After pip install boltons or copying iterutils.py into your project, just do:
from boltons.iterutils import remap
drop_falsey = lambda path, key, value: bool(value)
clean = remap(metadata, visit=drop_falsey)
This page has many more examples, including ones working with much larger objects from Github's API.
It's pure-Python, so it works everywhere, and is fully tested in Python 2.7 and 3.3+. Best of all, I wrote it for exactly cases like this, so if you find a case it doesn't handle, you can bug me to fix it right here.
Based on Ryan's solution, if you also have lists and nested dictionaries:
For Python 2:
def remove_empty_from_dict(d):
if type(d) is dict:
return dict((k, remove_empty_from_dict(v)) for k, v in d.iteritems() if v and remove_empty_from_dict(v))
elif type(d) is list:
return [remove_empty_from_dict(v) for v in d if v and remove_empty_from_dict(v)]
else:
return d
For Python 3:
def remove_empty_from_dict(d):
if type(d) is dict:
return dict((k, remove_empty_from_dict(v)) for k, v in d.items() if v and remove_empty_from_dict(v))
elif type(d) is list:
return [remove_empty_from_dict(v) for v in d if v and remove_empty_from_dict(v)]
else:
return d
BrenBarn's solution is ideal (and pythonic, I might add). Here is another (fp) solution, however:
from operator import itemgetter
dict(filter(itemgetter(1), metadata.items()))
If you have a nested dictionary, and you want this to work even for empty sub-elements, you can use a recursive variant of BrenBarn's suggestion:
def scrub_dict(d):
if type(d) is dict:
return dict((k, scrub_dict(v)) for k, v in d.iteritems() if v and scrub_dict(v))
else:
return d
For python 3
dict((k, v) for k, v in metadata.items() if v)
Quick Answer (TL;DR)
Example01
### example01 -------------------
mydict = { "alpha":0,
"bravo":"0",
"charlie":"three",
"delta":[],
"echo":False,
"foxy":"False",
"golf":"",
"hotel":" ",
}
newdict = dict([(vkey, vdata) for vkey, vdata in mydict.iteritems() if(vdata) ])
print newdict
### result01 -------------------
result01 ='''
{'foxy': 'False', 'charlie': 'three', 'bravo': '0'}
'''
Detailed Answer
Problem
Context: Python 2.x
Scenario: Developer wishes modify a dictionary to exclude blank values
aka remove empty values from a dictionary
aka delete keys with blank values
aka filter dictionary for non-blank values over each key-value pair
Solution
example01 use python list-comprehension syntax with simple conditional to remove "empty" values
Pitfalls
example01 only operates on a copy of the original dictionary (does not modify in place)
example01 may produce unexpected results depending on what developer means by "empty"
Does developer mean to keep values that are falsy?
If the values in the dictionary are not gauranteed to be strings, developer may have unexpected data loss.
result01 shows that only three key-value pairs were preserved from the original set
Alternate example
example02 helps deal with potential pitfalls
The approach is to use a more precise definition of "empty" by changing the conditional.
Here we only want to filter out values that evaluate to blank strings.
Here we also use .strip() to filter out values that consist of only whitespace.
Example02
### example02 -------------------
mydict = { "alpha":0,
"bravo":"0",
"charlie":"three",
"delta":[],
"echo":False,
"foxy":"False",
"golf":"",
"hotel":" ",
}
newdict = dict([(vkey, vdata) for vkey, vdata in mydict.iteritems() if(str(vdata).strip()) ])
print newdict
### result02 -------------------
result02 ='''
{'alpha': 0,
'bravo': '0',
'charlie': 'three',
'delta': [],
'echo': False,
'foxy': 'False'
}
'''
See also
list-comprehension
falsy
checking for empty string
modifying original dictionary in place
dictionary comprehensions
pitfalls of checking for empty string
Building on the answers from patriciasz and nneonneo, and accounting for the possibility that you might want to delete keys that have only certain falsy things (e.g. '') but not others (e.g. 0), or perhaps you even want to include some truthy things (e.g. 'SPAM'), then you could make a highly specific hitlist:
unwanted = ['', u'', None, False, [], 'SPAM']
Unfortunately, this doesn't quite work, because for example 0 in unwanted evaluates to True. We need to discriminate between 0 and other falsy things, so we have to use is:
any([0 is i for i in unwanted])
...evaluates to False.
Now use it to del the unwanted things:
unwanted_keys = [k for k, v in metadata.items() if any([v is i for i in unwanted])]
for k in unwanted_keys: del metadata[k]
If you want a new dictionary, instead of modifying metadata in place:
newdict = {k: v for k, v in metadata.items() if not any([v is i for i in unwanted])}
I read all replies in this thread and some referred also to this thread:
Remove empty dicts in nested dictionary with recursive function
I originally used solution here and it worked great:
Attempt 1: Too Hot (not performant or future-proof):
def scrub_dict(d):
if type(d) is dict:
return dict((k, scrub_dict(v)) for k, v in d.iteritems() if v and scrub_dict(v))
else:
return d
But some performance and compatibility concerns were raised in Python 2.7 world:
use isinstance instead of type
unroll the list comp into for loop for efficiency
use python3 safe items instead of iteritems
Attempt 2: Too Cold (Lacks Memoization):
def scrub_dict(d):
new_dict = {}
for k, v in d.items():
if isinstance(v,dict):
v = scrub_dict(v)
if not v in (u'', None, {}):
new_dict[k] = v
return new_dict
DOH! This is not recursive and not at all memoizant.
Attempt 3: Just Right (so far):
def scrub_dict(d):
new_dict = {}
for k, v in d.items():
if isinstance(v,dict):
v = scrub_dict(v)
if not v in (u'', None, {}):
new_dict[k] = v
return new_dict
To preserve 0 and False values but get rid of empty values you could use:
{k: v for k, v in metadata.items() if v or v == 0 or v is False}
For a nested dict with mixed types of values you could use:
def remove_empty_from_dict(d):
if isinstance(d, dict):
return dict((k, remove_empty_from_dict(v)) for k, v in d.items() \
if v or v == 0 or v is False and remove_empty_from_dict(v) is not None)
elif isinstance(d, list):
return [remove_empty_from_dict(v) for v in d
if v or v == 0 or v is False and remove_empty_from_dict(v) is not None]
else:
if d or d == 0 or d is False:
return d
"As I also currently write a desktop application for my work with Python, I found in data-entry application when there is lots of entry and which some are not mandatory thus user can left it blank, for validation purpose, it is easy to grab all entries and then discard empty key or value of a dictionary. So my code above a show how we can easy take them out, using dictionary comprehension and keep dictionary value element which is not blank. I use Python 3.8.3
data = {'':'', '20':'', '50':'', '100':'1.1', '200':'1.2'}
dic = {key:value for key,value in data.items() if value != ''}
print(dic)
{'100': '1.1', '200': '1.2'}
Dicts mixed with Arrays
The answer at Attempt 3: Just Right (so far) from BlissRage's answer does not properly handle arrays elements. I'm including a patch in case anyone needs it. The method is handles list with the statement block of if isinstance(v, list):, which scrubs the list using the original scrub_dict(d) implementation.
#staticmethod
def scrub_dict(d):
new_dict = {}
for k, v in d.items():
if isinstance(v, dict):
v = scrub_dict(v)
if isinstance(v, list):
v = scrub_list(v)
if not v in (u'', None, {}, []):
new_dict[k] = v
return new_dict
#staticmethod
def scrub_list(d):
scrubbed_list = []
for i in d:
if isinstance(i, dict):
i = scrub_dict(i)
scrubbed_list.append(i)
return scrubbed_list
An alternative way you can do this, is using dictionary comprehension. This should be compatible with 2.7+
result = {
key: value for key, value in
{"foo": "bar", "lorem": None}.items()
if value
}
Here is an option if you are using pandas:
import pandas as pd
d = dict.fromkeys(['a', 'b', 'c', 'd'])
d['b'] = 'not null'
d['c'] = '' # empty string
print(d)
# convert `dict` to `Series` and replace any blank strings with `None`;
# use the `.dropna()` method and
# then convert back to a `dict`
d_ = pd.Series(d).replace('', None).dropna().to_dict()
print(d_)
Some of Methods mentioned above ignores if there are any integers and float with values 0 & 0.0
If someone wants to avoid the above can use below code(removes empty strings and None values from nested dictionary and nested list):
def remove_empty_from_dict(d):
if type(d) is dict:
_temp = {}
for k,v in d.items():
if v == None or v == "":
pass
elif type(v) is int or type(v) is float:
_temp[k] = remove_empty_from_dict(v)
elif (v or remove_empty_from_dict(v)):
_temp[k] = remove_empty_from_dict(v)
return _temp
elif type(d) is list:
return [remove_empty_from_dict(v) for v in d if( (str(v).strip() or str(remove_empty_from_dict(v)).strip()) and (v != None or remove_empty_from_dict(v) != None))]
else:
return d
metadata ={'src':'1921','dest':'1337','email':'','movile':''}
ot = {k: v for k, v in metadata.items() if v != ''}
print(f"Final {ot}")
You also have an option with filter method:
filtered_metadata = dict( filter(lambda val: val[1] != u'', metadata.items()) )
Some benchmarking:
1. List comprehension recreate dict
In [7]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
...: dic = {k: v for k, v in dic.items() if v is not None}
1000000 loops, best of 7: 375 ns per loop
2. List comprehension recreate dict using dict()
In [8]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
...: dic = dict((k, v) for k, v in dic.items() if v is not None)
1000000 loops, best of 7: 681 ns per loop
3. Loop and delete key if v is None
In [10]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
...: for k, v in dic.items():
...: if v is None:
...: del dic[k]
...:
10000000 loops, best of 7: 160 ns per loop
so loop and delete is the fastest at 160ns, list comprehension is half as slow at ~375ns and with a call to dict() is half as slow again ~680ns.
Wrapping 3 into a function brings it back down again to about 275ns. Also for me PyPy was about twice as fast as neet python.