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