Reputation: 97
I thought I set out a simple project for myself but I guess not. I think im using the Ordered dict function long because I keep getting:
ValueError: too many values to unpack (expected 2)
Code:
import random
import _collections
shop = {
'bread': 2,
'chips': 4,
'tacos': 5,
'tuna': 4,
'bacon': 8,
}
print(shop)
'''
items = list(shop.keys())
random.shuffle(items)
_collections.OrderedDict(items)
'''
n = random.randrange(0, len(shop.keys()))
m = random.randrange(n, len(shop.keys()))
if m <= n:
m += 1
print(n, " ", m)
for key in shop.keys():
value = shop[key] * random.uniform(0.7,2.3)
print(key, "=", int(value))
if n < m:
n += 1
else:
break
I would like for this code to mix up the dictionary, then multiply the values by 0.7 - 2.3. Then loop within the range 0-5 times in order to give me few random keys from the dictionary.
I have placed ''' ''' over the code that I struggle with and gives me the errors.
Upvotes: 1
Views: 1324
Reputation: 6989
You are very close, but you cannot just give the list of keys ot the new OrderedDict
, you must give the values too... try this:
import random
import collections
shop = {
'bread': 2,
'chips': 4,
'tacos': 5,
'tuna': 4,
'bacon': 8,
}
print(shop)
items = list(shop.keys())
random.shuffle(items)
print(items)
ordered_shop = collections.OrderedDict()
for item in items:
ordered_shop[item] = shop[item]
print(ordered_shop)
Example output:
{'chips': 4, 'tuna': 4, 'bread': 2, 'bacon': 8, 'tacos': 5}
['bacon', 'chips', 'bread', 'tuna', 'tacos']
OrderedDict([('bacon', 8), ('chips', 4), ('bread', 2), ('tuna', 4), ('tacos', 5)])
You could also do this like this (as pointed out by @ShadowRanger):
items = list(shop.items())
random.shuffle(items)
oshop = collections.OrderedDict(items)
This works because the OrderedDict
constructor takes a list of key-value tuples. On reflection, this is probably what you were after with your initial approach - swap keys()
for items()
.
Upvotes: 3
Reputation: 1847
d = collections.OrderedDict.fromkeys(items)
And then use newly created dict d
as you wish.
Upvotes: 1