python - 重新分配字典值

标签 python dictionary

我有一本像这样的字典

{'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''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])))

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

最佳答案

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

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) 的运行时间,因为使用索引操作手动排序列表是一个线性操作,而不是 sorted这将是 O(n log n)。

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

关于python - 重新分配字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50665866/

相关文章:

arrays - 类型 Any 在 Swift 3.0 中没有下标成员错误?

Python 从 CSV 创建字典并使用文件名作为键

python - Pandas Columns to Flattened Dictionary(而不是字典列表)

python - Django 自定义静态文件未收集到 s3 存储桶

python - 如何将多个用户名和密码作为字典添加到密码文件中?

dictionary - 任何免费的英语-西类牙语单词数据库?

python - 从 Python 字典中的 key 中删除元素

python - flask Python中的for循环

python - 有没有办法制作列表的列表,然后删除该列表中的第一项?

python - 需要使用输入将 Excel 文件中同一行中的值相乘