简体   繁体   中英

Dict with curly braces and OrderedDict

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.

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() .

d = collections.OrderedDict.fromkeys(items)

然后根据需要使用新创建的dict d

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