user103657
user103657

Reputation: 3

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.

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?

I apologize if I got something wrong.

Upvotes: 0

Views: 102

Answers (1)

Sven Eberth
Sven Eberth

Reputation: 3116

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}}

Upvotes: 1

Related Questions