gpt4 book ai didi

python - 如何将嵌套字典变成矩阵列表?

转载 作者:行者123 更新时间:2023-12-02 05:39:57 25 4
gpt4 key购买 nike

我有以下字典:

dictionary = {'test1.txt': {'apple': 1, 'banana': 1, 'lemon': 1},
'test2.txt': {'apple': 1, 'banana': 1},
'test3.txt': {'apple': 1, 'lemon': 2},
'test4.txt': {'apple': 1, 'lemon': 1, 'grape': 1}}

应该变成:

[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'],
['lemon', 1, 0, 2, 1],
['apple', 1, 1, 1, 1],
['banana', 1, 1, 0, 0],
['grape', 0, 0, 0, 1]]

我已经尝试了下面的代码,但我总是遇到错误:

keycount = []                                                                      
for i, f in enumerate(dictionary):
for t in f:
if t not in keycount:
keycount[t] = [0]*len(dictionary)
vocabulary[t][i]+=1

有没有人知道如何解决这个问题? 请不要使用外部库,我只是在练习:)

最佳答案

没有外部库

dictionary = {'test1.txt': {'apple': 1, 'banana': 1, 'lemon': 1},
'test2.txt': {'apple': 1, 'banana': 1},
'test3.txt': {'apple': 1, 'lemon': 2},
'test4.txt': {'apple': 1, 'lemon': 1, 'grape': 1}}

# all the keys used by all dictionaries
#all_keys = set().union(*(d.keys() for d in dictionary.values()))
# update using @JonClements suggestion
all_keys = set().union(*dictionary.values())

# Start with list of keys
lst = [list(dictionary.keys())]

# Add item count from each dictionary
lst += [[k] + [d.get(k, 0) for d in dictionary.values()] for k in all_keys]
print(lst)

输出

[['test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'], 
['banana', 1, 1, 0, 0],
['apple', 1, 1, 1, 1],
['lemon', 1, 0, 2, 1],
['grape', 0, 0, 0, 1]]

关于python - 如何将嵌套字典变成矩阵列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60020243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com