[PYTHON] dict in dict Makes a dict a dict

Regarding the subject, I will report that it was implemented by a python beginner. In the first place, a dict in dict is a dict like the one below.

{'name': '2M2VgARX', 'js': {'a': 0, 'b': 0, 'c': 'sdmo'}}

The in dict key and the in dict key are unique even if they are combined, so I wanted to combine them into one dictionary, so I created such a function.

Image after conversion

{'name': '2M2VgARX', 'js_a': 0, 'js_b': 0, 'js_c': 'sdmo'}

There seems to be a standard function, but my search ability is low, so Please note that it was not found.

Implementation

import secrets
import string


def dict_extract(item, prefix=''):
    return_dict = {}
    for key, value in item.items():
        if isinstance(value, dict):
            prefix += f'{key}_'
            return_dict.update(dict_extract(value, prefix))
        else:
            return_dict[prefix + key] = value
    return return_dict


def main():
    # create sample data
    items =[]
    alphabet = string.ascii_letters + string.digits
    password = ''.join(secrets.choice(alphabet) for i in range(8))
    for i in range(10):
        password = ''.join(secrets.choice(alphabet) for i in range(8))
        tmp = {'a': i, 'b': i*2, 'c': 'sdmo'}
        tmp_item = {'name': password, 'js': tmp}
        items.append(tmp_item)

    # print dict
    for item in items:
        print(dict_extract(item))


if __name__ == "__main__":
    main()

Execution result

{'name': 'ZQ4NaBbc', 'js_a': 0, 'js_b': 0, 'js_c': 'sdmo'}
{'name': 'E5hS6IqS', 'js_a': 1, 'js_b': 2, 'js_c': 'sdmo'}
{'name': 'PC1xzQGi', 'js_a': 2, 'js_b': 4, 'js_c': 'sdmo'}
{'name': 'McJTGCjl', 'js_a': 3, 'js_b': 6, 'js_c': 'sdmo'}
{'name': '3hYsdwB8', 'js_a': 4, 'js_b': 8, 'js_c': 'sdmo'}
{'name': 'UKocBVhJ', 'js_a': 5, 'js_b': 10, 'js_c': 'sdmo'}
{'name': '3QVlhwOn', 'js_a': 6, 'js_b': 12, 'js_c': 'sdmo'}
{'name': 'bspVE4Hp', 'js_a': 7, 'js_b': 14, 'js_c': 'sdmo'}
{'name': 'rLLUxF4f', 'js_a': 8, 'js_b': 16, 'js_c': 'sdmo'}
{'name': '5wt3UCvR', 'js_a': 9, 'js_b': 18, 'js_c': 'sdmo'}

Commentary

Digression

I feel that it is smarter to join with prefix as list. In that case, avoid passing list as an argument. list is a mutable, updatable object. If you specify a mutable object as the initial value of the argument, that object is created when the function is defined, so if you call the function with the corresponding argument omitted, the same object will be used.

code

def string_arg2(s_arg=['hatsumi']):
    s_arg.append(' san')
    print(''.join(s_arg))

for i in range(10):
    string_arg2()

result

hatsumi san
hatsumi san san
hatsumi san san san
hatsumi san san san san
hatsumi san san san san san
hatsumi san san san san san san
hatsumi san san san san san san san
hatsumi san san san san san san san san
hatsumi san san san san san san san san san
hatsumi san san san san san san san san san san

The result is like a business card management service. By the way, dict is also mutable, so be careful. It takes a lot of work to initialize.

def string_arg2(s_arg=None):
    if s_arg is None:
        s_arg = ['hatsumi']
    s_arg.append(' san')
    print(''.join(s_arg))

for i in range(10):
    string_arg2()

Recruitment

--There seems to be a standard function of the above implementation. I would be grateful if you could tell me how to find it. .. ――Is there a general name for dict in dict? Nested dictionary? It becomes d in d for short, and it looks like docker in docker and is confusing ...

Recommended Posts

dict in dict Makes a dict a dict
Sort dict in dict (dictionary in dictionary) with a specific key
Take a screenshot in Python
Create a function in Python
Create a dictionary in Python
Collaborate in a remote environment
Use list-keyed dict in Python
Make a bookmarklet in Python
Draw a heart in Python
Run a multi-line script in a PDB
I get a UnicodeDecodeError in mecab-python3
Maybe in a python (original title: Maybe in Python)
Count specific strings in a file
Write a binary search in Python
Write a table-driven test in C
[python] Manage functions in a list
Hit a command in Python (Windows)
Create a CSV reader in Flask
Try throwing a query in Redash
Create a DI Container in Python
Is there a special in scipy? ??
I get a KeyError in pyclustering.xmeans
A note about get_scorer in sklearn
Implement a date setter in Tkinter
ABC166 in Python A ~ C problem
Write A * (A-star) algorithm in Python
Handle requests in a separate process
Save a specific variable in tensorflow.session
Create a binary file in Python
python / Make a dict from a list.
Solve ABC036 A ~ C in Python
Start SQLite in a programming language
Write a pie chart in Python
Write a vim plugin in Python
Write a depth-first search in Python
Implementing a simple algorithm in Python 2
Create a Kubernetes Operator in Python
Save a YAML-formatted file in PyYAML
Solve ABC037 A ~ C in Python
Run a simple algorithm in Python
Draw a CNN diagram in Python
When creating a matrix in a list
I put in a Bash called Powerline-shell that makes me crazy
Make a curtain generator in Blender
Create a random string in Python
Schedule a Zoom meeting in Python
When writing a program in Python
Create a LINE Bot in Django
Get a Boolean in Flask's request
Generate a first class collection in Python
Install Django in a pipenv virtual environment
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
Solve ABC175 A, B, C in Python
Use print in a Python2 lambda expression
A simple HTTP client implemented in Python
I want to print in a comprehension
Precautions when pickling a function in python
Write the test in a python docstring
Display a list of alphabets in Python 3
Display matplotlib diagrams in a web application
Try sending a SYN packet in Python