What is the best way to implement nested dictionaries?

后端 未结 21 1829
[愿得一人]
[愿得一人] 2020-11-22 00:29

I have a data structure which essentially amounts to a nested dictionary. Let\'s say it looks like this:

{\'new jersey\': {\'mercer county\': {\'plumbers\':          


        
21条回答
  •  花落未央
    2020-11-22 00:30

    You could create a YAML file and read it in using PyYaml.

    Step 1: Create a YAML file, "employment.yml":

    new jersey:
      mercer county:
        pumbers: 3
        programmers: 81
      middlesex county:
        salesmen: 62
        programmers: 81
    new york:
      queens county:
        plumbers: 9
        salesmen: 36
    

    Step 2: Read it in Python

    import yaml
    file_handle = open("employment.yml")
    my_shnazzy_dictionary = yaml.safe_load(file_handle)
    file_handle.close()
    

    and now my_shnazzy_dictionary has all your values. If you needed to do this on the fly, you can create the YAML as a string and feed that into yaml.safe_load(...).

提交回复
热议问题