我碰壁了
我需要搜索一个特定的值并输出该值所在的整个字典:
这是我的原版字典:
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}}
以参数1995,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}]}
这是我的代码:
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)
再次感谢!
你可以使用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()
输出:
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) = {}
您可以这样做。您可以查看注释行来了解您的错误。:
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)
输出:
{1995: [{'Division': 'Perth', 'Staff number': 10, 'Year formed': 1995}, {'Division': 'Brisbane', 'Staff number': 15, 'Year formed': 1995}]}