[PYTHON] Extract the value of dict or list as a string

I sometimes wanted to extract the values of dict and list using period-separated strings such as a.b and c.d.2.e, so I wrote them.

def get_item(src, path):
    now = src
    for i in path.split('.'):
        if type(now) is list:
            now = now[int(i)]
        else:
            now = now[i]
    return now

now is a variable to put the current value. The initial value is the argument dict or list. Divide the path by a period and turn it by for. Swap the value of now until the end of for and finally return.

By the way, I don't expect the Key name to have a period.

my_dict = {
    'a': {
        'b': 'hello'
    },
    'c': {
         'd':[
             {'e': 3},
             {'e': 4},
             {'e': 5},
             {'e': 6},
         ]
     }
}

print(get_item(my_dict, 'a.b'))
print(get_item(my_dict, 'c.d.3.e'))
print(get_item(my_dict, 'c.d'))
# hello
# 6
# [{'e': 3}, {'e': 4}, {'e': 5}, {'e': 6}]

Recommended Posts

Extract the value of dict or list as a string
Get the variable name of the variable as a character string.
How to connect the contents of a list into a string
Extract the value closest to a value from a Python list element
Precautions when using a list or dictionary as the default argument
String conversion of a list containing numbers
A note on customizing the dict list class
Make a copy of the list in Python
Search by the value of the instance in the list
Do not specify a mutable object (list type, dictionary type, etc.) as the initial value of the function argument of python.
Cut a part of the string using a Python slice
Make a note of the list of basic Pandas usage
# Function that returns the character code of a string
Output the output result of sklearn.metrics.classification_report as a CSV file
Get the output value of the command (as received by xargs)
Find out the apparent width of a string in python
Extract the Azure service list
Get the value of a specific key up to the specified index in the dictionary list in Python
Get the number of specific elements in a python list
Find the index of the maximum value (minimum value) of a multidimensional array
How to get the last (last) value in a list in Python
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
Addictive note: max (max (list)) must not be used when maxing the value of a 2D array
Save the result of the life game as a gif with python
Extract the index of the original set list that corresponds to the list of subsets.
Find the optimal value of a function with a genetic algorithm (Part 2)
Format when passing a long string as an argument of python
If you give a list with the default argument of the function ...
How to find the memory address of a Pandas dataframe value
How to extract the desired character string from a line 4 commands
Try using Elasticsearch as the foundation of a question answering system
Dig the directory and create a list of directory paths + file names
Finding the optimum value of a function using a genetic algorithm (Part 1)
Get the formula in an excel file as a string in Python
[Python] A program that rotates the contents of the list to the left
Find the definition of the value of errno
Extract the maximum value with pandas.
About the return value of pthread_mutex_init ()
python / Make a dict from a list.
About the return value of the histogram.
Generate a list of consecutive characters
About the basics list of Python basics
The story of writing a program
Sort the list that contains the dict
Python> Extract (unpack) the value of list> Add *> You taught me the difference between Python 2 and Python 3 regarding print (* mylist) / print ().
Extension of Python by C or C ++ (when there are multiple arguments, when passing a list from the Python side)
The story of making a slackbot that outputs as gif or png when you send the processing code
Python> Slice> A slice offset earlier than the beginning of a string is treated as 0, and one after the end is treated as -1
How to input a character string in Python and output it as it is or in the opposite direction.
Generate a list packed with the number of days in the current month.
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[Linux] Command to get a list of commands executed in the past
I measured 6 methods to get the index of the maximum value (minimum value) of the list
I want to sort a list in the order of other lists
Push the hash list into VT and receive the detection result as a list
Receive a list of the results of parallel processing in Python with starmap
The eval () function that calculates a string as an expression in python
Find the minimum value of a function by particle swarm optimization (PSO)
How to format a list of dictionaries (or instances) well in Python
I tried to display the altitude value of DTM in a graph
<Python> A quiz to batch convert file names separated by a specific character string as part of the file name