我想将文本文件中的特定行添加到字典中。 这个想法是将所有以AUD开头的行添加到AUD字典中,并用它们的键。 然后加入CAD并下载列表。
我已经尝试了一些搜索和增加一点点的变体。 我对答案很好奇,因为我是错误,他们在学习时意味着什么。 我在Python的开始,并且如果我的尝试使你的眼睛流血而道歉。 非常感谢您的时间。
这是.txt文件pastebin的格式
这将一切都添加到字典中,我只想要AUD
with open('rates.txt') as f: for line in f: if line.startswith('AUD') == True: # returns true on pairs I want to add AUD = dict(x.rstrip().split(None, 1) for x in f) #adds everything else: pass print AUD接下来我尝试了这个返回“ValueError:需要多个值来解压缩”
AUD = {} with open("rates.txt") as f: for line in f: if line.startswith('AUD'): (key, val) = line.split(' ') #The space inbetween the '' causes the error? AUD[int(key)] = val print AUD最后我正在处理这个返回'KeyError:'AUD_CHF'
AUD = {} with open("rates.txt") as f: for line in f: if 'AUD_' in line: key, value = line.strip().split('') AUD [key].append(value) print AUDI want to add specific lines from a text file into a dictionary. The idea would be to add all the lines beginning with AUD into an AUD dictionary, with their keys. Then CAD and down the list.
I've tried a few variants from searching and adding little bits. I'm as curious about answer as I am the errors and what they mean as I am learning. I am at the begining of Python and apologise if my attempts make your eyes bleed. Very grateful for your time.
This is the format of the .txt file pastebin
This adds everything to a dictionary, I only want AUD
with open('rates.txt') as f: for line in f: if line.startswith('AUD') == True: # returns true on pairs I want to add AUD = dict(x.rstrip().split(None, 1) for x in f) #adds everything else: pass print AUDNext I tried this which returned "ValueError: need more than 1 value to unpack"
AUD = {} with open("rates.txt") as f: for line in f: if line.startswith('AUD'): (key, val) = line.split(' ') #The space inbetween the '' causes the error? AUD[int(key)] = val print AUDand lastly I was working on this which returns 'KeyError: 'AUD_CHF'
AUD = {} with open("rates.txt") as f: for line in f: if 'AUD_' in line: key, value = line.strip().split('') AUD [key].append(value) print AUD最满意答案
你第一个例子很接近你。
你不需要if语句中的== True ,因为str.startswith()返回一个布尔值,这个布尔值被if所忽略。 随着我纠正了一些缩进。
AUD = {} with open('rates.txt', 'r') as f: for line in f: if line.startswith('AUD'): split_line = line.split() AUD[split_line[0]] = split_line[1] else: pass print AUDYou were close in you first example.
You don't need the == True in the if statement because str.startswith() returns a boolean which is evaulated by the if. Along with that I corrected some indentation.
AUD = {} with open('rates.txt', 'r') as f: for line in f: if line.startswith('AUD'): split_line = line.split() AUD[split_line[0]] = split_line[1] else: pass print AUD更多推荐
发布评论