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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.