Reputation: 3719
I have a data dictionary with eeg, gyroscope and other data. For processing, I want to extract eeg and gyroscope data in seperate dicts. Therefore I have two lists with the keys of eeg and gyroscope. I made it work with two dict comprehensions, but maybe there is a smoother solution to this.
eegKeys = ["FP3", "FP4"]
gyroKeys = ["X", "Y"]
# 'Foo' is ignored
data = {"FP3": 1, "FP4": 2, "X": 3, "Y": 4, "Foo": 5}
eegData = {x: data[x] for x in data if x in eegKeys}
gyroData = {x: data[x] for x in data if x in gyroKeys}
print(eegData, gyroData) # ({'FP4': 2, 'FP3': 1}, {'Y': 4, 'X': 3})
Upvotes: 13
Views: 21758
Reputation: 71
If you are in Python 3, an updated inline solution could be:
second_dict = dict((d, first_dict.pop(d)) for d in split_keys)
pop
would gently remove elements from the first dict and the generator with create the mapping to be passed to the dict constructor. Also you can use the good old dict comprehension.
Upvotes: 7
Reputation: 7230
Minor modifications, but this should be only a little bit cleaner:
eegKeys = ["FP3", "FP4"]
gyroKeys = ["X", "Y"]
# 'Foo' is ignored
data = {"FP3": 1, "FP4": 2, "X": 3, "Y": 4, "Foo": 5}
filterByKey = lambda keys: {x: data[x] for x in keys}
eegData = filterByKey(eegKeys)
gyroData = filterByKey(gyroKeys)
print(eegData, gyroData) # ({'FP4': 2, 'FP3': 1}, {'Y': 4, 'X': 3})
Or, if you prefer an one-liner:
eegKeys = ["FP3", "FP4"]
gyroKeys = ["X", "Y"]
# 'Foo' is ignored
data = {"FP3": 1, "FP4": 2, "X": 3, "Y": 4, "Foo": 5}
[eegData, gyroData] = map(lambda keys: {x: data[x] for x in keys}, [eegKeys, gyroKeys])
print(eegData, gyroData) # ({'FP4': 2, 'FP3': 1}, {'Y': 4, 'X': 3})
Upvotes: 12
Reputation: 1121962
No, two dict comprehensions are pretty much it. You can use dictionary views to select the keys that are present, perhaps:
eegData = {key: data[key] for key in data.keys() & eegKeys}
gyroData = {key: data[key] for key in data.keys() & gyroKeys}
Use data.viewkeys()
if you are using Python 2 still.
Dictionary views give you a set-like object, on which you can then use set operations; &
gives you the intersection.
Note that your approach, using key in eegKeys
and key in gyroKeys
could be sped up by inverting the loop (loop over the smaller list, not the bigger dictionary):
eegData = {key: data[key] for key in eegKeys if key in data}
gyroData = {key: data[key] for key in gyroKeys if key in data}
Upvotes: 10