简体   繁体   English

使用来自用户的输入从嵌套字典中检索字典列表

[英]Retrieving a list of Dictionaries from Nested Dictionary with an Input from User

I'm a bit new to Python and I'm working with Python 3. What I want to do is to retrieve a list of dictionaries, from the nested dictionary, with a similar key to what the user will input.我对 Python 有点陌生,我正在使用 Python 3. 我想要做的是从嵌套字典中检索字典列表,其键与用户输入的键相似。

Here's what I'm doing这就是我正在做的

import pickle
import os
os.system("cls")

p_inputs = {
 'DOE, JOHN': {'SEX': 'MALE', 'AGE': 18},
 'DOE, JANE': {'SEX': 'FEMALE', 'AGE': 18},
 'WEST, MARIA': {'SEX': 'FEMALE', 'AGE': 18}}

print("Please enter the necessary information.")
new_name = input("\nFULL NAME, SURNAME FIRST: ").upper()
new_sex =  input("SEX: ").upper()
new_age = int(input("AGE: "))

p_inputs[new_name] = {'SEX': new_sex, 'AGE': new_age,}
pickle.dump(p_inputs, open("info", "wb"))

Now, what should I do when I insert a line where I ask for the user's input, for example, I'm asking for the age.现在,当我在要求用户输入的地方插入一行时,我应该怎么做,例如,我要求年龄。 Then the user will type "18", how do I get a list of all the dictionaries of people with the AGE of 18?然后用户将输入“18”,我如何获得年龄为 18 岁的人的所有字典的列表?

I apologize if I got something wrong.如果我做错了什么,我深表歉意。

First you need to load the existing data like this:首先,您需要像这样加载现有数据:

with open("info", "rb") as f:
    p_inputs = pickle.load(f)

then you can do a dictionary comprehension:然后你可以做一个字典理解:

>>> {k: v for k,v in p_inputs.items() if v["AGE"] == 18}
{'name2': {'SEX': 'sex1', 'AGE': 18}, 'name3': {'SEX': 'sex2', 'AGE': 18}}

Btw: Currently you override evertime the dict and store only the newest person.顺便说一句:目前,您每次都覆盖字典并仅存储最新的人。


Edit: Full solution编辑:完整解决方案

import os
import pickle

os.system("cls")

try:
    with open("info", "rb") as f:
        p_inputs = pickle.load(f)
except FileNotFoundError:
    p_inputs = {}

print("Please enter the necessary information.")
new_name = input("\nFULL NAME, SURNAME FIRST: ").upper()
new_sex = input("SEX: ").upper()
new_age = int(input("AGE: "))

p_inputs[new_name] = {'SEX': new_sex, 'AGE': new_age}
with open("info", "wb") as f:
    pickle.dump(p_inputs, f)

print("Added")
print()

search_age = int(input("Show people with this age: "))
search_result = {k: v for k, v in p_inputs.items() if v["AGE"] == search_age}
print(search_result)

Input/Output输入输出

Please enter the necessary information.

FULL NAME, SURNAME FIRST: DOE, JOHN
SEX: MALE
AGE: 18
Added

Show people with this age: 18
{'DOE, JANE': {'SEX': 'FEMALE', 'AGE': 18}, 'DOE, JOHN': {'SEX': 'MALE', 'AGE': 18}, 'WEST, MARIA': {'SEX': 'FEMALE', 'AGE'
: 18}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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