Home > Back-end >  how to use hashmap for string and dictionary in python
how to use hashmap for string and dictionary in python

Time:10-19

I want to implement a use case through hashmap in python. I will be having a json object of type dict.

x={
  "name": "Jim",
  "age": 30,
  "married": True,
  "phonenumber": "123456"
  "pets": None,
  "cars": [
    {"model": "toyota", "mpg": 23.5},
    {"model": "kia", "mpg": 21.1}
  ]
}
if (x["married"] == True):
h.put(x[phonenumber]) // i want to make phonenumber as key and the entire dict x as value. by using something like Map<String, dict> h = new HashMap<>();

when i do h.get(phonenumber), i want the entire dict x as an output. How can i implement this usecase in python.

CodePudding user response:

A dict is python's version of a hash map. To do what you want, try the following:

m = {}
if x["married"]:
    m[x["phonenumber"]] = x

CodePudding user response:

As has already been said, the dict() is Python's implementation of hastmaps / hash tables. I've assumed that you are going to have many records, all of which will be stored in a dict(), and that you are adding records according to your example. I have not error-checked for the existence of a phone number in the record; since you're using the phone number as the key then you should already have ensured that there is an actual phone number in the information which you are adding.

#just one record
x={
    "name": "Jim",
    "age": 30,
    "married": True,
    "phonenumber": "123456",   #you left out a comma here
    "pets": None,
    "cars": [
        {"model": "toyota", "mpg": 23.5},
        {"model": "kia", "mpg": 21.1}
    ]
}

my_dict = dict()   #this would hold ALL of your records

def add_to_mydict(my_dict:dict, new_record:dict):
    if new_record["married"]:
        phone = new_record.pop("phonenumber")
        y = {phone: new_record}
        my_dict.update(y)

add_to_mydict(my_dict, x)
print(my_dict)

my_dict would be the master dictionary in which you will store your data. SQLite makes a much better database than in-memory dicts.

  • Related