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})
Method 1: Split dictionary keys and values using inbuilt functions. Here, we will use the inbuilt function of Python that is . keys() function in Python, and . values() function in Python to get the keys and values into separate lists.
Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.
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})
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With