Skip to content

Commit 7412a98

Browse files
committed
Add dictionary key lookup utility
1 parent 5d14833 commit 7412a98

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

folium/utilities.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -490,3 +490,20 @@ def parse_options(**kwargs):
490490
return {camelize(key): value
491491
for key, value in kwargs.items()
492492
if value is not None}
493+
494+
495+
def dict_get(d, *keys):
496+
"""Return the field in dictionary d under the given keys.
497+
498+
Examples
499+
--------
500+
>>> dict_get({'hi': {'there': 42}}, 'hi', 'there')
501+
42
502+
503+
"""
504+
if len(keys) == 0:
505+
return d
506+
if not isinstance(d, dict):
507+
raise TypeError('The first argument should be a dictionary, not a {}.'
508+
.format(type(d)))
509+
return dict_get(d[keys[0]], *keys[1:])

tests/test_utilities.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
deep_copy,
1212
get_obj_in_upper_tree,
1313
parse_options,
14+
dict_get,
1415
)
1516

1617

@@ -154,3 +155,16 @@ def test_parse_options():
154155
assert parse_options(thing=None) == {}
155156
assert parse_options(long_thing=42) == {'longThing': 42}
156157
assert parse_options(thing=42, lst=[1, 2]) == {'thing': 42, 'lst': [1, 2]}
158+
159+
160+
def test_dict_get():
161+
assert dict_get({}) == {}
162+
assert dict_get({'hi': 'there'}) == {'hi': 'there'}
163+
assert dict_get({'hi': {'there': 42}}, 'hi', 'there') == 42
164+
assert dict_get({'hi': [1, 2, 3]}, 'hi') == [1, 2, 3]
165+
with pytest.raises(TypeError):
166+
dict_get({'hi': 42}, 'hi', 'wrong-key')
167+
with pytest.raises(TypeError):
168+
dict_get(42, 'wrong-key')
169+
with pytest.raises(KeyError):
170+
dict_get({'hi': 42}, 'wrong-key')

0 commit comments

Comments
 (0)