![](/img/trans.png)
[英]Converting a text file to python dictionary - one key and multiple values - with exclusion of one field
[英]Converting a file into a dictionary with one key and multiple values
我有一個數據文件,看起來像這樣:
我想將第一列設置為鍵,並將鍵之后的值設置為字典的值。
這是我使用的代碼,但沒有給我我想要的東西。
with open('data.txt', 'r') as f:
...:
...: for line in f:
...: items = line.split()
...: key, values = items[0], items[1:]
...: my_dict[int(key)] = values
假設您試圖用相同的鍵連接行中的其他值而不是覆蓋它們,則可以使用:
for line in f:
items = line.split()
key, values = int(items[0]), items[1:]
my_dict.setdefault(key, []).extend(values)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.