python - 带花括号的字典和 OrderedDict

标签 python python-3.x dictionary ordereddictionary

我以为我为自己设定了一个简单的项目,但我想不是。我认为我长期使用 Ordered dict 函数是因为我不断得到:

 ValueError: too many values to unpack (expected 2)

代码:

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

我希望此代码混合字典,然后将值乘以 0.7 - 2.3。然后在范围内循环 0-5 次,以便从字典中给我一些随机键。

我已将 ''' ''' 放在我纠结的代码上,并给出了错误。

最佳答案

你非常接近,但你不能只给出新的 OrderedDict 的键列表,你还必须给出值......试试这个:

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)

示例输出:

{'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)])

您也可以这样做(正如@ShadowRanger 所指出的):

items = list(shop.items())
random.shuffle(items)
oshop = collections.OrderedDict(items)

这是有效的,因为 OrderedDict 构造函数采用键值元组列表。回想起来,这可能是您最初采用的方法所追求的 - 将 keys() 替换为 items()

关于python - 带花括号的字典和 OrderedDict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47659689/

相关文章:

python - 将字典条目转换为变量

vb.net - 如何将值插入(字符串,列表(字符串))字典的列表部分?

python - 将段落中句子的第一个单词大写

python - 从字符串序列创建 Python lambda 函数

python-3.x - Cart-Pole Python 性能比较

python - 如何计算 Python 中字符串中集合的成员?

python - 查找具有最大属性值的对象的键

python - 我正在将 pygame 窗口嵌入到 Tkinter 中,如何操作 pygame 窗口?

python - 避免重复 Django URL

python - 满足我的应用程序脚本需求的最小 Python 构建?