简体   繁体   English

如何使用for循环遍历字典?

[英]How to iterate over a dictionary using for loops?

I want to decompress a dictionary and a list into a sentence. 我想将字典和列表解压缩为句子。 For example: 例如:

newlist = [1, 2, 3, 4, 5, 6]
new_dictionary = {'code': 2, 'help': 6, 'broken': 4, 'is': 3, 'please': 5, 'my': 1}

The original sentence is 'My code is broken please help' . 原始句子是'My code is broken please help' The list shows the positions that the words appear within the sentence. 列表显示单词在句子中出现的位置。 The dictionary stores the word and the position that the word associates with. 词典存储单词和单词与之关联的位置。

The goal is to iterate over the dictionary until the matches the number in the list. 目标是遍历字典,直到匹配列表中的数字。 Once this happens, the key that matches to the value is added to a list. 一旦发生这种情况,与值匹配的键将添加到列表中。 This will continue to happen until there are no more numbers in the list. 这将继续发生,直到列表中没有更多的数字为止。 The list is then converted into a string and printed to the user. 然后,该列表将转换为字符串并打印给用户。

I would imagine that something like this would be the solution: 我可以想象这样的解决方案:

for loop in range(len(newlist)):
    x = 0
    for k,v in new_dictionary.items():
         if numbers[x] == v:
              original_sentence.append(k)
         else:
              x = x + 1

print(original_sentence)

However, the code just prints an empty list. 但是,该代码仅显示一个空列表。 Is there any way of re-wording or re-arranging the for loops so that the code works? 有什么方法可以重新编写或重新排列for循环,以便代码可以工作?

Invert the dictionary and proceed. 反转字典并继续。 Try the following code. 请尝试以下代码。

>>> d = {'code': 2, 'help': 6, 'broken': 4, 'is': 3, 'please': 5, 'my': 1}
>>> numbers = [1, 2, 3, 4, 5, 6]
>>> d_inv = {v:k for k,v in d.items()}
>>> ' '.join([d_inv[i] for i in numbers])
'my code is broken please help'

I assume you don't want to invert the dictionary, so you can try something like this: 我假设您不想反转字典,因此可以尝试如下操作:

dictionary = {'code': 2, 'help': 6, 'broken': 4, 'is': 3, 'please': 5, 'my': 1}
numbers = [1, 2, 3, 4, 5, 6]

sentence = []
for number in numbers:
    for key in dictionary.keys():
        if dictionary[key] == number:
            sentence.append(key)
            break

Sorted the dict with using the values. 使用值对字典进行排序。

import operator
new_dictionary = {'code': 2, 'help': 6, 'broken': 4, 'is': 3, 'please': 5, 'my': 1}
sorted_x = sorted(new_dictionary.items(), key=operator.itemgetter(1))
print ' '.join(i[0] for i in sorted_x)

result 结果

'my code is broken please help'

The whole code in single line. 整个代码在一行中。

In [1]: ' '.join([item[0] for item in sorted(new_dictionary.items(), key=operator.itemgetter(1))])
Out[1]: 'my code is broken please help'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM