[英]Handling file reading and multiple values to a key in dictionary
How can I code to read the first line from a file and put it as a key value of a dictionary and keep reading next values in a iterative manner and put them as the values to the particular key they fall into in the file. 我该如何编码以从文件中读取第一行并将其作为字典的键值,并以迭代方式继续读取下一个值,并将其作为它们落入文件中的特定键的值。 Like example:
像例子:
Item Quality Cost Place
Ball 1 $12 TX
Umbrella 5 $35 NY
sweater 89 $100 LA
So here, the representation is my file. 因此,这里是我的文件。 When I read, I want the dictionary to be created as in the things in bold go as keys and when i keep reading lines below that, I would have them going as multiple values in the respective keys.
当我阅读时,我希望像粗体中的键那样创建字典,而当我继续阅读低于该数字的行时,我希望它们在各个键中作为多个值显示。
thanks 谢谢
Looks like you are describing a csv file with a space delimiter. 看起来您正在描述带有空格定界符的csv文件。 Something like this should work ( from the Python help ).
这样的事情应该可以工作( 来自Python帮助 )。
>>> import csv
>>> spamReader = csv.reader(open('eggs.csv', 'rb'), delimiter=' ', quotechar='|')
>>> for row in spamReader:
... print ', '.join(row)
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
In fact, the csv.DictReader
would be better in order to have each row as a dictionary with keys defined by the first row. 实际上,
csv.DictReader
会更好,以便将每一行都作为具有第一行定义的键的字典。
I am assuming that there is a newline inserted after each group of values. 我假设在每组值之后插入一个换行符。
Edit : Using the example above, we get: 编辑 :使用上面的示例,我们得到:
In [1]: import csv
In [2]: f = csv.DictReader(open('test.txt', 'r'), delimiter = ' ', skipinitialspace = True)
In [3]: for row in f: print row
{'Item': 'Ball', 'Cost': '$12', 'Quality': '1', 'Place': 'TX'}
{'Item': 'Umbrella', 'Cost': '$35', 'Quality': '5', 'Place': 'NY'}
{'Item': 'sweater', 'Cost': '$100', 'Quality': '89', 'Place': 'LA'}
Passing the parameter skipinitialspace = True
to the DictReader
is needed to be able to get rid of multiple spaces without creating spurious entries in each row. 需要将参数
skipinitialspace = True
传递给DictReader
,以便能够摆脱多个空格而又不会在每一行中创建虚假条目。
You can't have "multiple values" for a given key, but you can of course have one value per key that's a list. 给定键不能有“多个值”,但是每个键当然可以有一个列表值。
For example (Python 2.6 or better -- simply because I use the next
function for generality rather than methods such as readline
, but you can of course tweak that!): 例如(Python 2.6或更高版本-仅仅是因为我出于通用性考虑使用
next
函数,而不是诸如readline
方法,但是您当然可以对其进行调整!):
def makedictwithlists(f):
keys = next(f).split()
d = {}
for k in keys: d[k] = []
for line in f:
for k, v in zip(keys, line.split()):
d[k].append(v)
return d
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.