【问题标题】:Dict with curly braces and OrderedDict带花括号和 OrderedDict 的字典
【发布时间】:2017-12-05 17:49:29
【问题描述】:

我以为我为自己制定了一个简单的项目,但我想不是。我认为我长期使用 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。您只有一个字符串文字,看起来像使用 OrderedDict 的代码(并且做错了,尝试在键列表上调用 OrderedDict,甚至没有尝试使用构造的 OrderedDict)。

标签: python python-3.x dictionary ordereddictionary


【解决方案1】:

您非常接近,但您不能只给出新的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()

【讨论】:

  • 您可以通过将其设为items = list(shop.items()),执行随机播放,然后执行ordered_shop = collections.OrderedDict(items) 来简化操作,而不仅仅是随机播放键并需要稍后再次从shop 查找值。跨度>
【解决方案2】:
d = collections.OrderedDict.fromkeys(items)

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

【讨论】:

  • 这不会从 shop 字典中引入值。
  • 什么意思?
  • 结果是带有键的dict,但所有值都是None
猜你喜欢
  • 2017-01-15
  • 2011-12-29
  • 1970-01-01
  • 2012-01-10
  • 2017-02-25
  • 2016-03-22
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
相关资源
最近更新 更多