[英]How to create a dictionary based on odd and even values from another dictionary?
I have the following dictionary: 我有以下字典:
{'key1': [value1], 'key2': [value2], 'key3': [value3], 'key4': [value4] }
what I want to do is to use the values to create a new dictionary. 我想要做的是使用值来创建一个新的字典。 The value of the odd elements will be the new keys, and the value of the next element will be the new value of that key. 奇数元素的值将是新键,下一个元素的值将是该键的新值。 I mean: 我的意思是:
{'value1': [value2], 'value3': [value4]}
how can i do it? 我该怎么做? i would like to clarify that this is a small example, since dictionaries have hundreds of elements, therefore the solution should be scalable to dictionaries with any amount of elements. 我想澄清这是一个小例子,因为字典有数百个元素,因此解决方案应该可以扩展到具有任意数量元素的字典。
Assuming, that 1) no KeyError will occur, ie there are no odd-indexed dictionary values with the same values, and 2) you have even number of entries in your dict, I would do something like this: 假设1)没有KeyError会发生,即没有奇数索引的字典值具有相同的值,2)你的dict中有偶数个条目,我会这样做:
vals = my_dict.values()
new_dict = {}
for i in range(0, len(vals), 2):
new_dict[vals[i]] = vals[i+1]
But, as others pointed out, dictionaries don't actually have order, so it's a "let's say" solution. 但是,正如其他人所指出的那样,词典实际上并没有秩序,所以这是一个“让我们说”的解决方案。
Steps to follow: 要遵循的步骤:
Create a dictionary out of these two array. 从这两个数组中创建一个字典。
dictObj = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4' }; print (dictObj.keys()); evenArray = dictObj.keys()[1::2]; oddArray = dictObj.keys()[::2]; dictObjNew = dict(zip(evenArray, oddArray)) print dictObjNew
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.