小编use*_*374的帖子

Python-如何将.txt文件中的行转换为字典元素?

假设我有一个文件"stuff.txt",其中包含以下单独的行:q:5 r:2 s:7

我想从文件中读取这些行中的每一行,并将它们转换为字典元素,字母是键,数字是值.所以我想得到y = {"q":5,"r":2,"s":7}

我尝试过以下内容,但它只打印一个空字典"{}"

y = {} 
infile = open("stuff.txt", "r") 
z = infile.read() 
for line in z: 
    key, value = line.strip().split(':') 
    y[key].append(value) 
print(y) 
infile.close()
Run Code Online (Sandbox Code Playgroud)

python dictionary file

3
推荐指数
1
解决办法
5036
查看次数

python-搜索字典子列表; 将字典键转换为值

说我有以下字典(我正在使用的字典更多,更大):

dict1={1:["item", "word", "thing"], 2:["word", "item"], 3:["thing", "item", "item"]}
Run Code Online (Sandbox Code Playgroud)

并将字典中使用的每个单词存储在列表中:

all_words=["item", "word", "thing"]
Run Code Online (Sandbox Code Playgroud)

我想通过字典子列表运行列表中的每个单词,并返回找到它们的所有子列表的键,将它们存储在元组中.所以我想得到:

dict2={"item":(1, 2, 3), "word":(1, 2), "thing":(1, 3)}
Run Code Online (Sandbox Code Playgroud)

继承人我所拥有的:

dict2={}    
for word in all_words:
    for key, sublist in dict2.items():
        for word in sublist:
            if word not in sublist:
                dict2[word]=dict2[word]+key
            else:
                dict2[word]=key
Run Code Online (Sandbox Code Playgroud)

python search dictionary sublist

3
推荐指数
1
解决办法
931
查看次数

标签 统计

dictionary ×2

python ×2

file ×1

search ×1

sublist ×1