d = dict(a=1, b=2, c=3, d=4, e=5)
print(d)
d1 = {x: d[x] for x in d.keys() if x not in ['a', 'b']}
print(d1)
# Basic syntax:
{key: your_dict[key] for key in your_dict.keys() and {'key_1', 'key_2'}}
# Where this uses list comprehension for dictionaries to make a new dictionary
# with the keys that are found in the set
# Example usage:
your_dict = {'key_1': 1, 'key_2': 2, 'key_3': 3}
{key: your_dict[key] for key in your_dict.keys() and {'key_1', 'key_2'}}
--> {'key_1': 1, 'key_2': 2}
dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys }
>>> obj = { "a":1, "b":{"c":2,"d":3}}
>>> only(obj,["a","b.c"])
{'a': 1, 'b': {'c': 2}}
def only(object,keys):
obj = {}
for path in keys:
paths = path.split(".")
rec=''
origin = object
target = obj
for key in paths:
rec += key
if key in target:
target = target[key]
origin = origin[key]
rec += '.'
continue
if key in origin:
if rec == path:
target[key] = origin[key]
else:
target[key] = {}
target = target[key]
origin = origin[key]
rec += '.'
else:
target[key] = None
break
return obj
dict
friends = [
{'name': 'Sam', 'gender': 'male', 'sport': 'Basketball'},
{'name': 'Emily', 'gender': 'female', 'sport': 'Volleyball'}
]
# filter by column names
print([{key: friend[key] for key in friend.keys() if key in ["name", "sport"]} for friend in friends])
# filter by rows
print([a for a in friends if a["name"] in ["Sam"]])