0

I followed this post to create functions that get and set values into a nested dictionary given a list of keys: Access nested dictionary items via a list of keys?

# get a dict value with a list of nested keys
def getFromDict(dataDict, mapList):
    return reduce(lambda d, k: d[k], mapList, dataDict)


# set a dict value with a list of nested keys
def setInDict(dataDict, mapList, value):
    getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value

How would this be done Pythonically (2.x) using list comprehension or otherwise while avoiding reduce?

Community
  • 1
  • 1
ProGirlXOXO
  • 2,170
  • 6
  • 25
  • 47

3 Answers3

3

Your result is not a list, so a list comprehension is not possible. Try this:

def get_from_dict(data, keys):
    for key in keys:
        data = data[key]
    return data

def set_in_dict(data, keys, value):
    get_from_dict(data, keys[:-1])[keys[-1]] = value
Daniel
  • 42,087
  • 4
  • 55
  • 81
1

I think that the more pythonic way of doing this would be to use an explicit loop as was done in your original question. See this question here: Python alternative to reduce()

From the linked answer: Guido has recommended against using reduce() and explained why it's being moved to functools in python 3.x in the linked blog post.

He instead recommends doing something like:

def get_from_dict(data_dict, map_list):
    for key in map_list:
        data_dict = data_dict[key]
    return data_dict

def set_in_dict(data_dict, map_list, value):
    data_dict = get_from_dict(data_dict, map_list[:-1])
    data_dict[map_list[-1]] = value

because it's clearer what's going on.

noseworthy
  • 46
  • 1
  • 5
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/10205423) – jezrael Nov 14 '15 at 21:41
  • I've edited my answer to hopefully be more useful. Thanks for the tip @jezrael – noseworthy Nov 14 '15 at 22:35
0

What you already do is fine. You will not be able to do better because reduce basically iterates over something with an accumulator while basic list comprehension iterates over something without any accumulator.

However, if you make a string usage of such nested dictionaries, JSON should be the way to go. See http://docs.python-guide.org/en/latest/scenarios/json/

Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46