0

Is there a way in python to perform randomization between two lists within a list and have a dictionary returned?

For example, from:

[[1,2,3,4], ['a','b','c','d']]

to:

[{3:'a'}, {1:'d'}, {2:'c'}, {4:'b'}]

What's the best way to achieve this? Using a list comprehension? My two lists are actually very large, so I'm wondering whether there's a more efficient alternative.

3
  • Do you really want a list of singleton dictionaries, as your code suggests, or do you want a single dicitonary, as your text suggests? The former data structure seems rather pointless to me. Commented Aug 9, 2013 at 17:23
  • Do you really want a list of single-item dicts (which is the output you've asked for), or a single dict like {1: 'd', 2: 'a', 3: 'c', 4: 'b'}? Commented Aug 9, 2013 at 17:23
  • I want the list showed in the output because that's how an external program expects the list to be structured. Commented Aug 9, 2013 at 17:32

2 Answers 2

4
import random
keys, values = [[1,2,3,4], ['a','b','c','d']]
random.shuffle(values)
result =  [{k:v} for k, v in zip(keys, values)]

produces a list such as:

In [7]: result
Out[7]: [{1: 'd'}, {2: 'b'}, {3: 'c'}, {4: 'a'}]

A more memory-efficient alternative would be to use an iterator:

import itertools as IT
result = ({k:v} for k, v in IT.izip(keys, values))

The larger question is why you would want a sequence of tiny dicts. Wouldn't it be more useful to have one dict, such as the one produced by Steven Rumbalski's answer?

Or, if you really do just want a randomized pairing, perhaps an iterator of tuples would suffice:

result = IT.izip(keys, values)
Sign up to request clarification or add additional context in comments.

2 Comments

But how can I access the dictionaries in the list then?
You can loop through the items with for dct in result.
2

This creates a single dictionary rather than a list of single item dictionaries as your question requests. If you really want that, use unutbu's answer.

import random

a = [1,2,3,4]
b = ['a','b','c','d']

random.shuffle(a)
result = dict(zip(a, b))

If you cannot mutate your source lists:

dx = range(len(a))
random.shuffle(dx)
dict(zip((a[i] for i in dx), b))

2 Comments

This will result in a dict, not a list of dictionaries. (The OP's desired structure is kind of strange, so I was fooled too.)
@DSM: I missed that. I'll leave it as is because unutbu refers to it in his answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.