[英]How to add a key in a dictionary? (from existing data)
我目前正在嘗試使用不同的鍵創建字典。 到目前為止,這是我的代碼:
fh = open("plateau.txt", "r")
str=fh.read()
fh.close()
lines=str.split("\n")
d = dict()
currentKey = None
for line in lines:
if ":" in line:
currentKey = line.strip(":")
d[currentKey] = []
else:
d[currentKey].append(tuple(line.split(" ")))
print(d)
一旦我這樣做了,我就會收到一本字典:
{'map': [('39', '41')], 'hubs': [('21', '3', '1500', '25'), ('21', '38', '1500', '25')], 'peaks': [('10', '10', '200'), ('11', '10', '300'), ('12', '10', '400'), ('10', '11', '200'), ('10', '12', '500'), ('',)]}
我想保留map , hubs和peaks作為鍵,但要添加新的,以便 'x':每個中的第一個數字,'y':第二個數字,等等。我該怎么做? 我害怕弄亂我的代碼,因為我覺得我快到了! 謝謝您的幫助。
tuple(line.split(" "))
更改tuple(line.split(" "))
:
{ k:int(v) for k,v in zip(("x","y","z","health"),line.split(" ")) }
這將為您提供一些可能比在鍵之間難以匹配值的單獨鍵更容易操作的東西:
{
'map': [{"x":39, "y":41}],
'hubs': [{"x":21, "y":3, "z":1500, "health":25}, {"x":21, "y":38, "z":1500, "health":25}],
'peaks': ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.