Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split dictionary depending on key lists

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}) 
like image 567
ppasler Avatar asked Dec 26 '16 11:12

ppasler


People also ask

How do you split a dictionary key?

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.

Can dictionaries have lists as keys?

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.


2 Answers

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})
like image 71
Haroldo_OK Avatar answered Oct 01 '22 14:10

Haroldo_OK


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}
like image 20
Martijn Pieters Avatar answered Oct 01 '22 14:10

Martijn Pieters