如何解决python创建具有特定键名的字典,并从多行文本文件中为其分配值
嗨,我想用我自己的键名创建一个字典,并从具有多行的文本文件中为其分配值。每个条目均包含餐厅名称和食品类别。每个条目都由一行分隔。
我有一个包含以下值的文本文件:
Macdonalds
fast food
Sushiro
japanese food
我希望字典像这样
{ 'Restaurant name': [Macdonalds,Sushiro],'Food category': [fast food,japanese food] }
这些是我尝试过的代码:
with open("food.txt","r") as file:
dict = {}
for line in file:
line = line.split()
if not line:
continue
dict[line[0]] = line[1:]
print(dict)
显示此内容
{ 'macdonalds': [ ],'fast': ['food'] }
谢谢!!我是Python新手,非常感谢您的帮助
解决方法
假设有换行符分隔餐厅-食物条目,并假设您在所需字典中的字符串附近有一些引号,则可以执行以下操作:
#!/usr/bin/env python3
# Initialize a dictionary
my_dict = {
"Restaurant name": [],"Food category": []
}
# Open up a file named "input.txt"
with open('input.txt','r') as f:
# Read in a restaurant name
restaurant_name = f.readline().strip()
# Keep looping while there are more restaurants
while restaurant_name:
# Add the restaurant to our dictionary
my_dict["Restaurant name"].append(restaurant_name)
# Read in the food category and add it to our dictionary
my_dict["Food category"].append(f.readline().strip())
# Read in that blank line
f.readline()
# Read in the next restaurant name; will return none if there
# aren't any more lines,causing the loop to stop.
restaurant_name = f.readline().strip()
print(my_dict)
这将在末尾生成一个字典,如下所示:
{'Restaurant name': ['Macdonalds','Sushiro'],'Food category': ['fast food','japanese food']}
,
如果标志是“食物”
f = open('test.txt','r')
buffer = {'Restaurant name':[],'Food category':[]}
while True:
line = f.readline()
if not line:
break
if line == '\n':
continue
line = line.replace('\n','')
if 'food' in line:
buffer['Food category'].append(line)
else:
buffer['Restaurant name'].append(line)
print(buffer)
结果是
{'Restaurant name': ['Macdonalds','japanese food']}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。