简体   繁体   中英

Dynamically fill a python dictionary

How do I dynamically fill a dictionary in Python? For example, suppose I wanted to create a dictionary that held data from a tabulated format text file. Suppose I am creating an APR generator, and I have a list of individual traits with certain data stored as follows (income is rounded to some arbitrary value):

Neighborhood    Income     Risk_Factor    APR
Brighton        20000      10             .196
Allston         28500      3              .094
...

Now later, I want to do a lookup with a dictionary a certain individual:

Herman      Allston     25000    5

Now, I want to look up the APR to charge them from the dictionary. It would be checked by:

apr_charge["Allston"][25000][5] = 0.125

How would I create this dictionary dynamically? As in, now suppose I have another file for insurance, but now I don't take into account income. So I'd fill out the same type of dictionary with the same code, but now I have one less nested dictionary key. Is this possible? I want to create the nested dictionary without a priori knowledge of how deep the nest goes.

Edit: I realize a database could be used to store this information. I wanted to know if it's possible to handle this without use of a database. If it's not possible, I would need a light database that could store into memory. (The fewer dependency headaches, the better. I don't have complete control over the environment that this program would be running on.)

Use a database. It is easier than you might think.

sqlite would be a good choice:

  1. There would be no extra dependency since sqlite comes with Python.
  2. A database would allow for easier access to more flexible queries than with nested dicts. For example, you'd be able to ask, what neighborhoods have a risk_factor > 8? Or what what (neighborhood, income, risk_factor) tuples have APR < 0.10.
  3. Your data could live in a file and be in a format that could be read by other programs, even programs written in languages other than Python.
  4. As long as you don't expect many users trying to read or write to your database at the same time, sqlite should be quite satisfactory for this task.
  5. The sqlite3 database adapter has excellent documentation and conforms to the Python Database API Specification v2.0 .
  6. The SQL language as understood by SQLite has excellent documentation .

Here are some examples:

To create the database table:

import sqlite3

with sqlite3.connect('apr.sqlite') as connection:
    cursor = connection.cursor()
    cursor.execute('''CREATE TABLE aprtable
                      (id INTEGER PRIMARY KEY AUTOINCREMENT,
                      neighborhood TEXT,
                      income INTEGER,
                      risk_factor INTEGER,
                      apr FLOAT)''')

Or, to create the database in memory only:

with sqlite3.connect(':memory:') as connection:
    ....

To insert data into the table:

sql = 'INSERT INTO aprtable (neighborhood, income, risk_factor, apr) value (?,?,?,?)'
args = ['Brighton', 20000, 10, 0.196]
cursor.execute(sql, args)

Also check out the executemany method.

To find the apr given a neighborhood, income and risk_factor:

sql = 'SELECT apr FROM aprtable WHERE neighborhood = ? and income = ? and risk_factor = ?'
args = ['Allston', 25000, 5]
cursor.execute(sql, args)
row = cur.fetchone()
if row is not None:
    apr = row[0]

To change an apr given a neighborhood, income and risk_factor:

sql = 'UPDATE aprtable SET apr = ? WHERE neighborhood = ? and income = ? and risk_factor = ?'
args = [0.125, 'Allston', 25000, 5]
cursor.execute(sql, args)

To find what neighborhoods have risk_factor > 8:

sql = 'SELECT neighborhoods from aprtable where risk_factor > ?'
args = [8]
cursor.execute(sql, args)
neighborhoods = cur.fetchall()

To find what (neighborhood, income, risk_factor)s have APR < 0.10:

sql = 'SELECT neighborhood, income, risk_factor FROM aprtable WHERE apr < ?'
args = [0.10]
cursor.execute(sql, args)
for neighborhood, income, risk_factor in cursor:
    print(neighborhood, income, risk_factor)

Basically, just make the string the key, and then make the value anything else you want to store.

myDict = {}
for i in lines:
    myDict[i[0]] = lines[1:-1]

This way, you can check the apr just by using

myDict["Allston"][2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM