AlvinL
AlvinL

Reputation: 458

Extracting keys-values from dictionary

import random

dictionary = {'dog': 1,'cat': 2,'animal': 3,'horse': 4}
keys = random.shuffle(list(dictionary.keys())*3)
values = list(dictionary.values())*3
random_key = []
random_key_value = []

random_key.append(keys.pop())
random_key_value.append(???) 

For random_key_values.append, I need to add the value that corresponds to the key that was popped. How can I achieve this? I need to make use of multiples of the list and I can't multiply a dictionary directly, either.

Upvotes: 1

Views: 77

Answers (1)

Paco Abato
Paco Abato

Reputation: 4065

I'm going on python (you should specify the language in your question).

If I understand, you want to multiply the elements in the dictionary. So

list(dictionary.keys()) * 3

is not your solution: [1,2] * 3 results in [1,2,1,2,1,2]

Try instead list comprehension:

[i * 3 for i in dictionary.keys()] 

To take into account the order (because you shuffle it) shuffle the keys before the multiplication, then create the values list (in the same order that the shuffled keys) and finally multiply the keys:

keys = dictionary.keys()
random.shuffle(keys)
values = [dictionary[i]*3 for i in keys]
keys = [i * 3 for i in keys]

And finally:

random_key.append(keys.pop())
random_key_value.append(values.pop())

Also take care about the random function, it doesn't work as you are using it. See the documentation.

Upvotes: 2

Related Questions