如何使用for循环在基于另一个字典键的字典中查找键值对?

时间:2020-10-11 14:31:40

标签: python-3.x dictionary for-loop

我需要根据键在字典中找到键/值对。 有人可以解释一下怎么做吗?

按升序排列word_freq的键。 请根据word_freq创建新的字典word_freq2,并按升序对键进行排序。

有几种方法可以实现该目标,但是许多方法超出了我们到目前为止所学的范围。我们将描述采用您所学知识的一种方法。请随时使用此方式或您想要的任何其他方式。

首先,提取word_freq的键并将其转换为称为键的列表。

对键列表进行排序。

创建一个空字典word_freq2。

我无法为以下问题编写for循环。任何帮助将不胜感激 使用FOR循环迭代键中的每个值。对于每个迭代的键,在word_freq中找到相应的值,然后将键值对插入word_freq2。

word_freq = {'love': 25, 'conversation': 1, 'every': 6, "we're": 1, 'plate': 1, 'sour': 1, 'jukebox': 1, 'now': 11, 'taxi': 1, 'fast': 1, 'bag': 1, 'man': 1, 'push': 3, 'baby': 14, 'going': 1, 'you': 16, "don't": 2, 'one': 1, 'mind': 2, 'backseat': 1, 'friends': 1, 'then': 3, 'know': 2, 'take': 1, 'play': 1, 'okay': 1, 'so': 2, 'begin': 1, 'start': 2, 'over': 1, 'body': 17, 'boy': 2, 'just': 1, 'we': 7, 'are': 1, 'girl': 2, 'tell': 1, 'singing': 2, 'drinking': 1, 'put': 3, 'our': 1, 'where': 1, "i'll": 1, 'all': 1, "isn't": 1, 'make': 1, 'lover': 1, 'get': 1, 'radio': 1, 'give': 1, "i'm": 23, 'like': 10, 'can': 1, 'doing': 2, 'with': 22, 'club': 1, 'come': 37, 'it': 1, 'somebody': 2, 'handmade': 2, 'out': 1, 'new': 6, 'room': 3, 'chance': 1, 'follow': 6, 'in': 27, 'may': 2, 'brand': 6, 'that': 2, 'magnet': 3, 'up': 3, 'first': 1, 'and': 23, 'pull': 3, 'of': 6, 'table': 1, 'much': 2, 'last': 3, 'i': 6, 'thrifty': 1, 'grab': 2, 'was': 2, 'driver': 1, 'slow': 1, 'dance': 1, 'the': 18, 'say': 2, 'trust': 1, 'family': 1, 'week': 1, 'date': 1, 'me': 10, 'do': 3, 'waist': 2, 'smell': 3, 'day': 6, 'although': 3, 'your': 21, 'leave': 1, 'want': 2, "let's": 2, 'lead': 6, 'at': 1, 'hand': 1, 'how': 1, 'talk': 4, 'not': 2, 'eat': 1, 'falling': 3, 'about': 1, 'story': 1, 'sweet': 1, 'best': 1, 'crazy': 2, 'let': 1, 'too': 5, 'van': 1, 'shots': 1, 'go': 2, 'to': 2, 'a': 8, 'my': 33, 'is': 5, 'place': 1, 'find': 1, 'shape': 6, 'on': 40, 'kiss': 1, 'were': 3, 'night': 3, 'heart': 3, 'for': 3, 'discovering': 6, 'something': 6, 'be': 16, 'bedsheets': 3, 'fill': 2, 'hours': 2, 'stop': 1, 'bar': 1}


keys = list(word_freq.keys())  #extract the keys of word_freq and convert it to a list called keys
print(keys)            
            
    
for i in sorted (word_freq.keys()):  #Sort the keys list.
     print(i) 
        
        
word_freq2 = {} #Create an empty dictionary word_freq2

1 个答案:

答案 0 :(得分:1)

经过Python Dictionary Examples and Methods

之后,事实证明这是一个非常简单的解决方案
for value in keys:
    word_freq2[value] = word_freq.get(value)
print(word_freq2)

Python词典示例和方法。