как превратить вложенные словари в список матриц? - PullRequest
2 голосов
/ 01 февраля 2020

У меня есть следующий словарь:

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 

Кто-нибудь знает, как это решить? без внешних библиотек, пожалуйста, я просто практикуюсь с этим:)

Ответы [ 8 ]

3 голосов
/ 01 февраля 2020

Без внешних библиотек

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]]
2 голосов
/ 01 февраля 2020

Учитывая ваши исходные данные как:

d = {'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}}

Вы можете получить уникальные значения и немного транспонировать значения, например:

# Get all unique row_labels
keys = set().union(*d.values())
# Build up the rows to include zero values for items not present
rows = [[values.get(key, 0) for key in keys] for values in d.values()]
# Build the table with the header row and then each row_label with
# the transposed version of the values
table = [
    ['', *d], 
    *([key, *vals] for key, vals in zip(keys, zip(*rows)))
]

Это даст вам table как:

[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'],
 ['lemon', 1, 0, 2, 1],
 ['banana', 1, 1, 0, 0],
 ['apple', 1, 1, 1, 1],
 ['grape', 0, 0, 0, 1]]
2 голосов
/ 01 февраля 2020

Вы можете попробовать это.

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}}
val=list(dictionary.values())
uni=set()
for d in val:
    for i in d:
        uni.add(i) 
#uni will contain all the unique fruits

for key in uni:
    for d in val:
        new_dict.setdefault(key,[]).append(d.get(key,0))

res=['']+list(dictionary.keys())
out=[[k]+val for k,val in new_dict.items()]
fin=[res]+out
'''fin is 
['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt']
['grape', 0, 0, 0, 1]
['banana', 1, 1, 0, 0]
['apple', 1, 1, 1, 1]
['lemon', 1, 0, 2, 1]'''
2 голосов
/ 01 февраля 2020
# Data.
d = {'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}}

vocab = {}
for i, words in enumerate(d.values()):
    seen = set()
    for word, word_count in words.items():
        seen.add(word)
        if word not in vocab:
            vocab[word] = [0] * i  # If first time word is seen, add zero count for previously read files.
        vocab[word].append(word_count)
    # Add zero for previously encountered words not seen in file.
    for word in vocab:
        if word not in seen:
            vocab[word].append(0)

>>> [[''] + list(d.keys())] 
     + [[word] + word_counts for word, word_counts in vocab.items()]
[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'],
 ['apple', 1, 1, 1, 1],
 ['banana', 1, 1, 0, 0],
 ['lemon', 1, 0, 2, 1],
 ['grape', 0, 0, 0, 1]]
1 голос
/ 03 февраля 2020

Я знаю, что уже поздно, но так как я решил это, я хочу поделиться им.

fruits = ['lemon', 'apple', 'banana', 'grape']
fi = []
fi.append(fruits)
for k, v in d.items():
    li = []
    for i in ['lemon', 'apple', 'banana', 'grape']:
        li.append(v.get(i,0))
    fi.append(li)

print ([[i for i, v in d.items()]] + list(map(list, zip(*fi))))

# Result: [['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]]

Я надеюсь, что это помогает и имеет значение! :)

1 голос
/ 01 февраля 2020

Нет использования библиотеки

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}}

keycount = [['']]
keycount[0].extend(list(dictionary.keys()))
keys = dict()
for d_key in dictionary.keys():
    for i_key in dictionary[d_key].keys():
        if not i_key in keys:
            keys.update({i_key: True})

for key in keys:
    lists = [key]
    for d_key in dictionary.keys():
        lists.append(dictionary[d_key].get(key, 0))
    keycount.append(lists)
print(keycount)
1 голос
/ 01 февраля 2020

Это не использует внешние библиотеки и обобщает любой входной словарь указанной природы.

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}}

row_keys=[]
for x,v in dictionary.items():
  row_keys+=v.keys()
row_keys=list(set(row_keys))
dkeys=list(dictionary.keys())
header=['']+dkeys
rows=[]
for rk in row_keys:
  rows.append([rk])
  for k in dkeys:
    if rk in list(dictionary[k].keys()): rows[-1].append(dictionary[k][rk])
    else: rows[-1].append(0)
out=[header]+rows
print(out)
1 голос
/ 01 февраля 2020

Это не очень элегантно, но делает свою работу.

data = {'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}}

lemon = ['lemon']
apple = ['apple']
banana = ['banana']
grape = ['grape']
for key, value in data.items():
    print(key, value)
    if 'lemon' in value:
        lemon.append(value.get('lemon'))
    else:
        lemon.append(0)
    if 'apple' in value:
        apple.append(value.get('apple'))
    else:
        apple.append(0)
    if 'banana' in value:
        banana.append(value.get('banana'))
    else:
        banana.append(0)
    if 'grape' in value:
        grape.append(value.get('grape'))
    else:
        grape.append(0)

result = [list(data.keys()), lemon, apple, banana, grape]

Вывод:

[['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]]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...