如何在python中使用字符串和字典的hashmap



我想在python中通过hashmap实现一个用例。我将有一个dict.类型的json对象

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<>();

当我做h.get(电话号码(时,我想要整个dict x作为输出。我如何在python中实现这个用例。

dict是python版本的哈希映射。要做你想做的事,请尝试以下操作:

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

如前所述,dict()是Python对hastmaps/哈希表的实现。我假设您将有许多记录,所有这些记录都将存储在dict()中,并且您将根据您的示例添加记录。我没有错误地检查记录中是否存在电话号码;既然你使用的是电话号码作为密钥,那么你应该已经确保在你添加的信息中有一个实际的电话号码。

#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将是存储数据的主词典。SQLite使数据库比内存中的dicts要好得多。

最新更新