简体   繁体   中英

Shuffle a dictionary and list in unison?

I have a dictionary and list with same rows. I would like to shuffle the dictionary and list in unison that is with the same random seed.

test_dict = {3.0: deque([0.897, 24, 45]),
             2.0: deque([0.0, 0.5, 56]),
             9.0: deque([3.4, 0.9, 0.5])}

test_list = [deque([0.897, 24, 45]),
             deque([0.0, 0.5, 56]),
             deque([3.4, 0.9, 0.5])]

Is there a way to shuffle these two in the same order?

I tried the shuffle function from:

from random import shuffle
from sklearn.utils import shuffle

Both ended up giving an error. Is there a easier way to do this?

Edit: Since the values in the dictionary and elements in the list are same, I was wondering if we could shuffle the list and reassign them to the keys in the dictionary.

Since test_list simply contains the values in test_dict , you can shuffle it and then recreate the former from the results of the latter.

Note that if this correspondence between the two variables exists, having test_list is redundant — it's just list(test_dict.values()) .

from collections import deque
from pprint import pprint
from random import shuffle


test_dict = {3.0: deque([0.897, 24, 45]),
             2.0: deque([0.0, 0.5, 56]),
             9.0: deque([3.4, 0.9, 0.5])}

test_list = [deque([0.897, 24, 45]),
             deque([0.0, 0.5, 56]),
             deque([3.4, 0.9, 0.5])]

print('Before:')
pprint(test_dict, sort_dicts=False)
print('----')
pprint(test_list, width=40)

items = list(test_dict.items())
shuffle(items)
test_dict = dict(items)
test_list = list(test_dict.values())

print('\nAfter:')
pprint(test_dict, sort_dicts=False)
print('----')
pprint(test_list, width=40)

Results:

Before:
{3.0: deque([0.897, 24, 45]),
 2.0: deque([0.0, 0.5, 56]),
 9.0: deque([3.4, 0.9, 0.5])}
----
[deque([0.897, 24, 45]),
 deque([0.0, 0.5, 56]),
 deque([3.4, 0.9, 0.5])]

After:
{9.0: deque([3.4, 0.9, 0.5]),
 3.0: deque([0.897, 24, 45]),
 2.0: deque([0.0, 0.5, 56])}
----
[deque([3.4, 0.9, 0.5]),
 deque([0.897, 24, 45]),
 deque([0.0, 0.5, 56])]

PS An even shorter way to do it would be to use random.sample() instead of shuffle() :

test_dict = dict(random.sample(test_dict.items(), k=len(test_dict)))
test_list = list(test_dict.values())

The problem with what you're asking is that dictionaries do not have a defined order. You should think of a dictionary as a collection of (key,value) pairs that are unordered. Consider using a list of tuples if you want a well-defined order.

Also, avoid variable names like list and dict as they are keywords in Python!

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.

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