首页 > 解决方案 > 重新分配字典值

问题描述

我有一本像

{'A': 0, 'B': 1, 'C': 2, 'D': 3, etc}

如果字典未排序,如何从该字典中删除元素而不产生值间隙?

一个例子:

我有一个大矩阵,其中行代表单词,列代表遇到这些单词的文档。我将单词及其相应的索引存储为字典。例如对于这个矩阵

2 0 0
1 0 3
0 5 1
4 1 2

字典看起来像:

words = {'apple': 0, 'orange': 1, 'banana': 2, 'pear': 3}

如果我删除单词'apple'and 'banana',矩阵将只包含两行。所以'orange'字典中的值现在应该等于0而不是1,的值'pear'应该是1而不是3

在 Python 3.6+ 中,字典是有序的,所以我可以写这样的东西来重新分配值:

i = 0
for k, v in words.items():
  v = i
  i += 1

或者,或者,

words = dict(zip(terms.keys(), range(0, matrix.shape[0])))

我认为,这远不是更改值的最有效方法,而且它不适用于无序字典。如何有效地做到这一点?如果字典没有排序,有什么方法可以轻松地重新分配值?

标签: pythondictionary

解决方案


将 dict 转换为排序列表,然后构建一个没有要删除的单词的新 dict:

import itertools

to_remove = {'apple', 'banana'}

# Step 1: sort the words
ordered_words = [None] * len(words)
for word, index in words.items():
    ordered_words[index] = word
# ordered_words: ['apple', 'orange', 'banana', 'pear']

# Step 2: Remove unwanted words and create a new dict
counter = itertools.count()
words = {word: next(counter) for word in ordered_words if word not in to_remove}
# result: {'orange': 0, 'pear': 1}

这具有 O(n) 的运行时间,因为使用索引操作手动排序列表是线性操作,而不是sortedO(n log n)。

另请参阅itertools.count和的文档next


推荐阅读