Pass nested dictionary location as parameter in Python

2024/10/8 10:57:36

If I have a nested dictionary I can get a key by indexing like so:

>>> d = {'a':{'b':'c'}}
>>> d['a']['b']
'c'

Am I able to pass that indexing as a function parameter?

def get_nested_value(d, path=['a']['b']):return d[path]

Obviously, this is incorrect, I get TypeError: list indices must be integers, not str.

How can I do it correctly?

Answer

You can use reduce (or functools.reduce in python 3), but that would also require you to pass in a list/tuple of your keys:

>>> def get_nested_value(d, path=('a', 'b')):return reduce(dict.get, path, d)>>> d = {'a': {'b': 'c'}}
>>> get_nested_value(d)
'c'
>>> 

(In your case ['a']['b'] doesn't work because ['a'] is a list, and ['a']['b'] is trying to look up the element at "b"th index of that list)

https://en.xdnf.cn/q/70134.html

Related Q&A

Correct way to deprecate parameter alias in click

I want to deprecate a parameter alias in click (say, switch from underscores to dashes). For a while, I want both formulations to be valid, but throw a FutureWarning when the parameter is invoked with …

How to rename a file with non-ASCII character encoding to ASCII

I have the file name, "abc枚.xlsx", containing some kind of non-ASCII character encoding and Id like to remove all non-ASCII characters to rename it to "abc.xlsx".Here is what Ive t…

draw random element in numpy

I have an array of element probabilities, lets say [0.1, 0.2, 0.5, 0.2]. The array sums up to 1.0.Using plain Python or numpy, I want to draw elements proportional to their probability: the first eleme…

Python Gevent Pywsgi server with ssl

Im trying to use gevent.pywsgi.WSGIServer to wrap a Flask app. Everything works fine, however, when I try to add a key and a certificate for ssl, its not even able to accept any clients anymore.This is…

unexpected keyword argument buffering - python client

I am receiving the error as "getresponse() got an unexpected keyword argument buffering". Complete error log is :[INFO ] Kivy v1.8.0 [INFO ] [Logger ] Record lo…

numpy and pandas timedelta error

In Python I have an array of dates generated (or read from a CSV-file) using pandas, and I want to add one year to each date. I can get it working using pandas but not using numpy. What am I doing wron…

Pandas - split large excel file

I have an excel file with about 500,000 rows and I want to split it to several excel file, each with 50,000 rows.I want to do it with pandas so it will be the quickest and easiest.any ideas how to make…

Unable to verify secret hash for client at REFRESH_TOKEN_AUTH

Problem"Unable to verify secret hash for client ..." at REFRESH_TOKEN_AUTH auth flow. {"Error": {"Code": "NotAuthorizedException","Message": "Unab…

save a dependecy graph in python

I am using in python3 the stanford dependency parser to parse a sentence, which returns a dependency graph. import pickle from nltk.parse.stanford import StanfordDependencyParserparser = StanfordDepend…

What are the specific rules for constant folding?

I just realized that CPython seems to treat constant expressions, which represent the same value, differently with respect to constant folding. For example:>>> import dis >>> dis.dis(…