Hannnnn
Hannnnn

Reputation: 37

Making a dictionary from a list

I want to write a function that imports ascii_lowercase and returns a dictionary with the letters of keys as keys and a randomly shuffled version of the keys as values.

for example,

keys = "abcdefg..." 

and then you shuffle it and get gydwsk... as an example, and the dictionary should look like

{'a':'g', 'b':'y', 'c':'d'...}

Im not sure where to begin, any help is appreciated.

Upvotes: 0

Views: 68

Answers (4)

Paul Rooney
Paul Rooney

Reputation: 21609

A one liner. You can use random.sample to avoid the in place reordering nature of random.shuffle. Then combine the shuffled and non-shuffled values using zip, which can be passed directly to the dict constructor to make the new dict.

The use of alc as a shortening for ascii_lowercase is for brevity in the example and is probably a bit too brutal a shortening for most production code.

>>> from string import ascii_lowercase as alc
>>> from random import sample
>>> dict(zip(alc, sample(alc, len(alc))))
{'b': 'a', 's': 'w', 'v': 'g', 'g': 'n', 'k': 'v', 'c': 'h', 'h': 'j', 'u': 'f', 'd': 'i', 'n': 'p', 'x': 'y', 'r': 'm', 't': 'u', 'o': 's', 'j': 'e', 'e': 'c', 'l': 'b', 'y': 'z', 'q': 'k', 'z': 'd', 'f': 't', 'p': 'r', 'm': 'l', 'i': 'o', 'w': 'x', 'a': 'q'}

You will not see them in alphabetical order, but this is expected from an unordered container.

Upvotes: 1

Rafael
Rafael

Reputation: 1875

You need to shuffle it with random.shuffle. Here is an example:

import random

keys = 'abcdefghijklmnopqrdtuvxz'
shuffle_keys = list_keys = list(keys)

random.shuffle(shuffle_keys)

my_dict = dict(zip(keys, shuffle_keys))

print(my_dict)

Edited

Good suggestion for simpler dict construction (from comments. Thanks)

Upvotes: 1

almanegra
almanegra

Reputation: 663

This code should work (python version < 3.0):

import random
keys="abcdefg"
dictionary = {}
shuffled = ''.join(random.sample(keys,len(keys)))
shuffled_iterator = 0
for letter in keys:
  dictionary[letter] = shuffled[shuffled_iterator]
  shuffled_iterator +=1

print dictionary

Upvotes: 0

Joonazan
Joonazan

Reputation: 1416

import random

def f(keys):
    shuffled = list(keys)
    random.shuffle(shuffled)
    return dict(zip(keys, shuffled))

Upvotes: 0

Related Questions