繁体   English   中英

python 创建一个具有特定键名的字典,并从具有多行的文本文件中为其分配值

[英]python create a dictionary with specific key name and assign values to it from a text file with multiple lines

嗨,我想用我自己的键名创建一个字典,并从一个多行的文本文件中为其赋值。 每个条目由餐厅名称和食物类别组成。 每个条目由一行分隔。

我有一个包含这些值的文本文件:

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', 'Sushiro'], 'Food category': ['fast food', 'japanese food']}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM