0

I'm trying to make a very small "database" using dictionary in python, that will ultimately be stored as json/text.

Right now it only stores a key (str or int) and value as list of more dictionaries and lists. But since dict only stores two items (keys & values) is there away to add a 3rd item without creating a new dict or list for data retrieval? I thought of changing keys into list of two values, but don't know how I'd be able to searching though the keys. I don't want to add more list and dictionary making to more difficult to parse through.

Do I need to use something else instead of dictionary, or am I just thinking about it all wrong?

DataBase = [
    {9: [
        {1: [
            {100: "something"},
            {200: "something else"}
            ]
        },
        {2: [
            {112: "something different"},
            {153: "blank"}
            ]
        }
    ]
    },
    {99: [{}]},
    {100: [{}]}
]

In a nutshell what I'm trying to do is pull data from csv and spreadsheets, and put into some sort of a database to be able to easily read and write to. So I think this is the best I was able to come up with, don't know if I can improve it even further.

Ex: Country,USA, State, NY, City, NYC, Zip, 10001, Name, John

    {(Country, USA):
          {(State, NY):
               {(City, NYC):
                    {(Zip, 10001): {Name: John}, (Zip, 11001): {Name: Jane}}
                }
           {(State, LA): {(City, notNYC):
                    {(Zip, 00001): {Name: Joe, Name: Jame}
           }
    }
Da Jankee
  • 9
  • 5

1 Answers1

1

You may need to explain more, because I don't get why you only store one key-value pair in each dict.

It's possible to make multiple valued keys with tuples.

(key1, key2, key3, keyn) : "some value"

One way to search is by using filter.

database_triplets = {
             (1,2,3):"123",
             (1,3,2):"132",
             (2,9,8):"298"}

"""
partial_search(query, start_index = 0):
inputs:
     query: List with search terms.
     start_index: which index of key to look for the query (0 as default)
"""
def partial_search(query, start_index = 0):
    query_len =  len(query)

    """ tuples of lenght 1 are a little strange ie. (1,). 
        Therefore the input is list
    """
    query = tuple(query) 
    search_results =  list(filter(lambda x: x[start_index: start_index + query_len] == tuple(query), database_triplets))
    return search_results

# search for first partial key as 1 --> [(1,2,3), (1,3,2)]
print(partial_search([1])) 
# search for two last digits of partial key as [3,2] --> [1,3,2] 
print(partial_search([3,2], 1) 

You could probably simplify the database like this. It depend what you are trying to accomplish:

database =  {9: 
                {1:{100: "something",
                    200: "something else"},
                 2:{112: "something different", 
                    153: "blank"}},
             99: {},
             100:{}
}
zweistein
  • 98
  • 7