我正在编写一个简单的用于运动的解析器,但是在将下载的数据保存到字典时遇到问题。
data = {"":{"":[]}}
with open("Training_01.txt", "r") as open_file:
text = open_file.read()
text = text.split("\n")
for i in text:
i = i.split("/")
try:
data[i[1]] = {i[2]:[].append(i[3])}
except:
print("Can't")
这是我要解析的数据的示例:
/a/abbey/sun_aobrvxdhumowzajn.jpg
/a/abbey/sun_apstfzmbeiwbjqvb.jpg
/a/abbey/sun_apyilcssuybumhbu.jpg
/a/abbey/sun_arrohcvipmrghrzh.jpg
/a/abbey/sun_asgeghboyugsatii.jpg
/a/airplane_cabin/sun_blczihbhbntqccux.jpg
/a/airplane_cabin/sun_ayzaayjpoknjvpds.jpg
/a/airplane_cabin/sun_afuoinkozbbhqksk.jpg
/b/butte/sun_asfnwmuzhtjrztns.jpg
/b/butte/sun_ajzkngginlffsozz.jpg
/b/butte/sun_adonkmfgywrhpakt.jpg
/c/cabin/outdoor/sun_atqvmarllxqynnks.jpg
/c/cabin/outdoor/sun_acfcobswmnoyhyfi.jpg
/c/cabin/outdoor/sun_afgjdqosvakljsmc.jpg
我想用“ a”,“ b”,“ c”或任何字母作为键(我不能用硬编码)创建字典,并用字典作为包含拍摄图像的位置和图像列表的值的字典
但是当我想读取保存的数据时,我得到None
作为值
print(data["a"])
Output: {'auto_factory': None}
答案 0 :(得分:4)
尝试使用python stdlib中的defaultdict
。在这种情况下非常方便:
from collections import defaultdict
data = defaultdict(lambda: defaultdict(list))
with open("Training_01.txt", "r") as open_file:
text = open_file.read()
text = text.split("\n")
for line in text:
try:
_, key, subkey, rem = line.split("/", 3)
data[key][subkey].append(rem)
except:
print("Can't")
print(data)
说明:第一次使用不存在的密钥访问data
(这是字典)时,将为该密钥创建一个新条目。该条目将再次成为defaultdict,但是第一次尝试使用不存在的密钥进行访问时,将再次创建一个新的(这次嵌套)条目。并且此条目将为list
。因此,您可以安全地将新元素添加到此类列表中。
UPD:这是一种实现相同要求但没有defaultdict
的方法:
data = {} # just a plain dict
# for ...:
data[key] = data.get(key, {}) # try to access the key, if it doesn't exist - create a new dict entry for such a key
data[key][subkey] = data[key].get(subkey, []) # same as above but for the sub key
data[key][subkey].append(rem) # finally do the job
答案 1 :(得分:1)
因为每次data[i[1]] = {i[2]:[].append(i[3])}
都会创建一个新的第二层字典。
这是一个可能的解决方案。这是最干净的解决方案,但它会逐步显示。如果密钥不在最后一层字典中,它将创建一个新字典并列出。但是,如果dict有键,它将附加值到列表中。
data = {"":{"":[]}}
with open("Training_01.txt", "r") as open_file:
text = open_file.read()
text = text.split("\n")
for i in text:
i = i.split("/")
key_1 = i[1]
key_2 = i[2]
value = i[3]
try:
if key_1 in data.keys(): # Whether the key i[1] is in the 1st layer of the Dict
if key_2 in data[key_1].keys(): # Whether the key i[2] is in the 2nd layer of the Dict
# Yes, Append to the list
data[key_1][key_2].append(value)
else:
# No, Creat a new list
data[key_1][key_2] = [value]
# if i[1] not in the 1st layer, creat a 2nd layer dict with i[2] as key, i[3] as value
else:
data[key_1] = {key_2:[value]}
except:
print("Can't")
print(data['a'])