python - 从字典列表中获取键值

标签 python list dictionary

我有一个列表,其中包含带有字母和频率的词典。基本上,每个字母表(小写和大写)和空格我都有 53 部词典。

adict = {'Letter':'a', 'Frequency':0}
bdict = {'Letter':'b', 'Frequency':0}
cdict = {'Letter':'c', 'Frequency':0}

如果您输入一个单词,它会扫描该单词并更新其对应字母的频率。

for ex in range(0, len(temp)):
    if temp[count] == 'a': adict['Frequency']+=1
    elif temp[count] == 'b': bdict['Frequency']+=1
    elif temp[count] == 'c': cdict['Frequency']+=1

例如,我输入单词“Hello”,检测到字母 H、e、l、l、o 并更新其频率。非零频率将转移到新列表。

if adict['Frequency'] != 0 : newArr.append(adict) 
if bdict['Frequency'] != 0 : newArr.append(bdict)
if cdict['Frequency'] != 0 : newArr.append(cdict) 

在此之后,我将 newArr 按频率排序并转移到一个名为 finalArr 的新列表中。以下是单词“Hello”的示例列表内容

{'Letter': 'H', 'Frequency': 1}
{'Letter': 'e', 'Frequency': 1}
{'Letter': 'o', 'Frequency': 1}
{'Letter': 'l', 'Frequency': 2}

现在我想要的是仅将键值传输到 2 个单独的列表; letterArr 和 numArr。我该怎么做呢?我想要的输出是:

letterArr = [H,e,o,l]
numArr = [1,1,1,2]

最佳答案

你为什么不直接使用 collections.Counter ?例如:

from collections import Counter
from operator import itemgetter

word = input('Enter a word: ')
c = Counter(word)

letter_arr, num_arr = zip(*sorted(c.items(), key=itemgetter(1,0)))
print(letter_arr)
print(num_arr)

请注意使用 sorted() 按增加的频率进行排序。 itemgetter() 用于反转排序顺序,以便首先对频率执行排序,然后对字母执行排序。然后在解压列表中使用 zip() 将排序后的频率分开。

演示

Enter a word: Hello
('H', 'e', 'o', 'l')
(1, 1, 1, 2)

结果是元组,但如果需要,您可以使用 list(letter_arr)list(num_arr) 转换为列表。

关于python - 从字典列表中获取键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37088291/

相关文章:

python - Kivy 中的中心小部件

python - MySQLdb.cursors.Cursor.execute 在不同游标的情况下返回不同的值,为什么?

list - 在 F# 中过滤列表的最佳功能方式

dictionary - F#:在计时器上将项目添加到字典

c - 将列表和内部字典定义为c中字典的值

python - 我正在尝试使用 python 制作频率分析程序,但遇到问题

python - 从多个列表创建唯一的对象列表

c# - 为什么会有 List<T>.BinarySearch(...)?

c++ - Rcpp Armadillo : "-=" operation on list elements

python - 根据键值过滤python中的嵌套字典