简体   繁体   English

尝试按两个读取单列文本文件以在字典中创建键值对

[英]Trying to read a single column text file by two's to make a key-value pair in a dictionary

Working on a typical Python project of quizzing a user on state's capitals.从事一个典型的 Python 项目,对用户进行州首府的测验。 Instead of just copying and creating my own dictionary I'm reading a text file.我正在阅读一个文本文件,而不仅仅是复制和创建我自己的字典。 I have the portion of the quiz set up(I think) and I'm struggling with creating the actual key-value pairs.我已经设置了测验的一部分(我认为)并且我正在努力创建实际的键值对。 The text file looks like this:文本文件如下所示:

Alabama阿拉巴马州

Montgomery蒙哥马利

Alaska阿拉斯加州

Juneau朱诺

Arizona亚利桑那

Phoenix凤凰

Arkansas阿肯色州

Little Rock etc....小石城等……

I can't figure out how to read the first line as the key(state) and second line as the value(capital).我不知道如何将第一行读取为键(状态),将第二行读取为值(大写)。 Once I have the correct variables I will change what my main method calls.一旦我有了正确的变量,我将改变我的主要方法调用的内容。 Any help or feedback is appreciated.任何帮助或反馈表示赞赏。 Thanks!谢谢!

Here is my code:这是我的代码:

    NUM_STATES = 5

    def make_dictionary():
        with open('state_capitals.txt', 'r') as f:
           d = {}
           for line in f:
               d[line.strip()] = next(f, '').strip()

    def main():
        d = make_dictionary()

        correct = 0
        incorrect = 0

        for count in range(NUM_STATES):
            state, capital = d.popitem()

        print('Enter a capital of ', state, '?', end = '')
        response = input() 
        if response.lower() == capital.lower():
            correct += 1
            print('Correct!')
        else:
             incorrect += 1
             print('Incorrect.')

        print('The number of correct answers is: ', correct)
        print('The number of incorrect answers is: ', incorrect)


    main()

I would suggest reading the file as a string then do this我建议将文件作为字符串读取然后执行此操作

with open('state_capitals.txt', 'r') as f:
  file_ = f.read()

file_ = list(filter(lambda x:not x == "", file_.split("\n")))

keys = [key for index,key in enumerate(file_) if index%2 == 0]
values = [value for index,value in enumerate(file_) if not index%2 == 0]

dictionary = dict(zip(keys, values))
print(dictionary)

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

相关问题 如何在变量中提取字典单键值对 - How to extract dictionary single key-value pair in variables 从字典中读取 file_path 并稍后在管道中使用另一个键值对 - Read file_path from dictionary and use another key-value pair later in the pipeline 使用两个字符串填充字典以生成键值对 - Populating a dictionary using two strings to generate the key-value pair 如何将两列值转换为键值对字典? - How to convert two columns values into a key-value pair dictionary? 给定键值对,从字典中派生项目 - Given key-value pair(s), derive the item from a dictionary 如何使用json文件形成带有键值对的字典 - how to form a dictionary with key-value pair using a json file 将 QueryDict 转换为键值对字典 - Convert QueryDict to key-value pair dictionary 尝试将列表转换为 python 中的字典时出现问题,但它仅从列表中提取最后一个键值对 - Getting issue while trying to convert a list to a dictionary in python but it's extracting only the last key-value pair from the list 如何使用(相同长度和相同键)两个不同字典的值创建一个新字典,用作键值对 - How to make a new dictionary from the values of (same lengths and same keys) two different dictionaries, using as key-value pair 如何使用pandas读取文本文件的键值对? - How to read text file's key, value pair using pandas?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM