What is the best way to implement nested dictionaries?

后端 未结 21 1809
[愿得一人]
[愿得一人] 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:36

    As others have suggested, a relational database could be more useful to you. You can use a in-memory sqlite3 database as a data structure to create tables and then query them.

    import sqlite3
    
    c = sqlite3.Connection(':memory:')
    c.execute('CREATE TABLE jobs (state, county, title, count)')
    
    c.executemany('insert into jobs values (?, ?, ?, ?)', [
        ('New Jersey', 'Mercer County',    'Programmers', 81),
        ('New Jersey', 'Mercer County',    'Plumbers',     3),
        ('New Jersey', 'Middlesex County', 'Programmers', 81),
        ('New Jersey', 'Middlesex County', 'Salesmen',    62),
        ('New York',   'Queens County',    'Salesmen',    36),
        ('New York',   'Queens County',    'Plumbers',     9),
    ])
    
    # some example queries
    print list(c.execute('SELECT * FROM jobs WHERE county = "Queens County"'))
    print list(c.execute('SELECT SUM(count) FROM jobs WHERE title = "Programmers"'))
    

    This is just a simple example. You could define separate tables for states, counties and job titles.

提交回复
热议问题