Quantcast
Channel: How to use a dot "." to access members of dictionary? - Stack Overflow
Viewing all articles
Browse latest Browse all 40

Answer by pbanka for How to use a dot "." to access members of dictionary?

$
0
0

The language itself doesn't support this, but sometimes this is still a useful requirement. Besides the Bunch recipe, you can also write a little method which can access a dictionary using a dotted string:

def get_var(input_dict, accessor_string):"""Gets data from a dictionary using a dotted accessor-string"""    current_data = input_dict    for chunk in accessor_string.split('.'):        current_data = current_data.get(chunk, {})    return current_data

which would support something like this:

>> test_dict = {'thing': {'spam': 12, 'foo': {'cheeze': 'bar'}}}>> output = get_var(test_dict, 'thing.spam.foo.cheeze')>> print output'bar'>>

Viewing all articles
Browse latest Browse all 40

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>