I've hit a wall.
I need to search for a particular value and output the whole dictionary that the value is in:
This is my Original dictionary:
dictionary1={ "Perth":{"Division": "Perth","Staff number":10,"Year formed":1995},"Darwin":{"Division": "Darwin","Staff number":5,"Year formed":2000},"Brisbane":{"Division": "Brisbane","Staff number":15,"Year formed":1995}}
After calling the function with the argument 1995,year_formed_data(1995)
, the output should be:
{1995:[{"Division": "Perth","Staff number":10,"Year formed":1995},{"Division": "Brisbane","Staff number":15,"Year formed":1995}]}
Likewise if:
year_formed_data(2000)
{2000:[{"Division": "Darwin","Staff number":5,"Year formed":2000}]}
This is my code:
def year_formed_data(yr):
year={}
for business,data in dictionary1.items():
if data ==yr:
year[yr]={list({"Division": ,"Staff number": ,"Year formed": }
print(year)
year_formed_data(1995)
Thanks again!
CodePudding user response:
You could maybe utilize collections.defaultdict
:
from collections import defaultdict
DATA = {
'Perth': {'Division': 'Perth', 'Staff number': 10, 'Year formed': 1995},
'Darwin': {'Division': 'Darwin', 'Staff number': 5, 'Year formed': 2000},
'Brisbane': {'Division': 'Brisbane', 'Staff number': 15, 'Year formed': 1995},
}
def year_formed_data(yr: int) -> dict:
year_data = defaultdict(list)
for city, data in DATA.items():
if data['Year formed'] == yr:
year_data[yr].append(data)
return dict(year_data)
def main() -> None:
print(f'{year_formed_data(1995) = }')
print(f'{year_formed_data(2000) = }')
print(f'{year_formed_data(2005) = }')
if __name__ == '__main__':
main()
Output:
year_formed_data(1995) = {1995: [{'Division': 'Perth', 'Staff number': 10, 'Year formed': 1995}, {'Division': 'Brisbane', 'Staff number': 15, 'Year formed': 1995}]}
year_formed_data(2000) = {2000: [{'Division': 'Darwin', 'Staff number': 5, 'Year formed': 2000}]}
year_formed_data(2005) = {}
CodePudding user response:
Here's how you can do it. You can see the commented lines to understand your mistakes. :
dictionary1={ "Perth":{"Division": "Perth","Staff number":10,"Year formed":1995},"Darwin":{"Division": "Darwin","Staff number":5,"Year formed":2000},"Brisbane":{"Division": "Brisbane","Staff number":15,"Year formed":1995}}
def year_formed_data(yr):
year={}
year[yr] = [] # Create a list for that particular year to store required data.
for business, data in dictionary1.items():
# data was in the form of a dictionary. You are required to extract `Year formed` from that.
if (data['Year formed'] == yr):
# Append the Division, Staff, Year formed if yr matches.
year[yr].append({"Division": data['Division'] ,"Staff number": data['Staff number'], "Year formed": data['Year formed']})
print(year)
year_formed_data(1995)
Output:
{1995: [{'Division': 'Perth', 'Staff number': 10, 'Year formed': 1995}, {'Division': 'Brisbane', 'Staff number': 15, 'Year formed': 1995}]}