Filter dict to contain only certain keys?
Constructing a new dict:
dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys }
Uses dictionary comprehension.
If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((your_key, old_dict[your_key]) for ...)
. It's the same, though uglier.
Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for old_dict
s of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict.
Removing everything in-place:
unwanted = set(keys) - set(your_dict)
for unwanted_key in unwanted: del your_dict[unwanted_key]
filter items in a python dictionary where keys contain a specific string
How about a dict comprehension:
filtered_dict = {k:v for k,v in d.iteritems() if filter_string in k}
One you see it, it should be self-explanatory, as it reads like English pretty well.
This syntax requires Python 2.7 or greater.
In Python 3, there is only dict.items()
, not iteritems()
so you would use:
filtered_dict = {k:v for (k,v) in d.items() if filter_string in k}
Filter a dictionary to return certain keys
You can create a dictionary with needed keys and their respective values via dictionary comprehension and add it to new_list
#List of keys you need
needed_keys = ['trip_distance', 'pickup_latitude', 'pickup_longitude']
#Iterate over trips list
for trip in trips:
#Create a dictionary with needed keys and their respective values and add it to result
new_list.append({k:trip[k] for k in needed_keys})
How to to filter dict to select only keys greater than a value?
[v for k,v in mydict.items() if k >= 6]
Filter Json Keys that contains certain character in Python
This can be accomplished with a dict comprehension, which can be updated based on your needed filter:
new_dict = {key: value for key, value in info['store'].items() if "book" in key}
Filter dictionary based on list of keys
Simply:
d2 = {k:d[k] for k in lst}
But all keys must exist in the source directory. If not:
d2 = {k:d[k] for k in lst if k in d}
Python: How to select and then compare and filter certain values in a dict?
You don't need the sorted list of keys.
result = sorted(newdict.items(), key=lambda x: x[1], reverse=True)[:3]
This returns a list of (key, value)
tuples.
Python filter nested Dict
Since you have a nested dictionary, your filtering logic also has to be nested. Here's an example that works with the sample data you've provided and returns the filtered data in its original structure:
new_dict = {
"clients": [{
"name": client["name"],
"data": {
"gender": client["data"]["gender"],
"telephones": [
phone
for phone in client["data"].get("telephones", [])
if "home" in phone
]
}
} for client in client_dict["clients"]]
}
If you wanted to do it without hardcoding the specific structure, a recursive function is a good way to handle arbitrary nesting. Here's an example with a function that takes a set of keys to include; this produces a slightly nicer result than the hard-coded version because it can filter out the empty telephones
list if there's no home phone given:
def filter_nested_dict(obj, keys):
if isinstance(obj, list):
new_list = []
for i in obj:
new_i = filter_nested_dict(i, keys)
if new_i:
new_list.append(new_i)
return new_list
if isinstance(obj, dict):
new_dict = {}
for k, v in obj.items():
if k not in keys:
continue
new_v = filter_nested_dict(v, keys)
if new_v:
new_dict[k] = new_v
return new_dict
return obj
new_dict = filter_nested_dict(
client_dict,
{"clients", "name", "data", "gender", "telephones", "home"}
)
from pprint import pprint
pprint(new_dict)
Result:
{'clients': [{'data': {'gender': 'Male'}, 'name': 'John A'},
{'data': {'gender': 'Male',
'telephones': [{'home': '1234567890'}]},
'name': 'John B'}]}
Related Topics
How Does Asyncio Actually Work
Convert Python Datetime to Epoch with Strftime
How to Use Python Requests to Fake a Browser Visit A.K.A and Generate User Agent
Passing a Dictionary to a Function as Keyword Parameters
Downloading a Picture via Urllib and Python
How to Get Method Parameter Names
Call a Function from Another File
Writing a Python List of Lists to a CSV File
Add a Prefix to All Flask Routes
How to Configure Chromedriver to Initiate Chrome Browser in Headless Mode Through Selenium
Using Quotation Marks Inside Quotation Marks
Handling Very Large Numbers in Python
Import CSV File as a Pandas Dataframe
Create Own Colormap Using Matplotlib and Plot Color Scale
Iterate Through Pairs of Items in a Python List
Pip Install from Pypi Works, But from Testpypi Fails (Cannot Find Requirements)