从字典中将项添加到字典中

时间:2014-04-03 16:10:24

标签: python dictionary

我想将一个项目从一个列表复制到另一个列表。例如:

chest = {}

chest["sword":1,3]
chest["gold":5]

inventory = {}

inventory.add(chest["sword"])    #example pseudo code

如何从"胸部"添加1项?到"库存",保留关键名称和值?

感谢您的帮助!

编辑以避免混淆:

我希望能够添加一个单一项目,比如"胸部"到"库存"。这样:

inventory = {}
chest = {"sword":1, "gold":5, "other item":"other data"}

我想从"胸部"中取出1件物品。 (取决于用户输入)并将其添加到"库存":

inventory.add( chest [ item_from_chest ] ) #exampe pseudo code

此库存世界看起来像这样:

>>>{"sword":1}

抱歉有任何疑惑,希望此编辑有所帮助!

2 个答案:

答案 0 :(得分:2)

最有可能的是,您需要一些合并算法才能不覆盖清单中的现有项目。类似的东西:

#! /usr/bin/python3.2

import random

prefices = ['', 'Shabby', 'Surreal', 'Gleaming', 'Muddy']
infices = ['Sword', 'Banana', 'Leather', 'Gloves', 'Tea Cup']
suffices = ['', 'of the Bat', 'of Destruction', 'of Constipation', 'of thy Mother']

def makeItem ():
    tokens = [random.choice (fix) for fix in (prefices, infices, suffices) ]
    return ' '.join (t for t in tokens if t)

def makeChest ():
    chest = {'Gold': random.randint (5, 20) }
    for _ in range (random.randint (0, 5) ):
        chest [makeItem () ] = 1
    return chest

inventory = {}
while True:
    chest = makeChest ()
    print ('\n\n\nThou hast found a chest containing: {}'.format (', '.join ('{} {}'.format (v, k) for k, v in chest.items () ) ) )
    r = input ('\nWhishest thou to pick up this apparel? [y/*] ')
    if r not in 'Yy': continue

    for k, v in chest.items ():
        try: inventory [k] += v
        except KeyError: inventory [k] = v

    print ('\n\nThy bag now containth:')
    for k, v in inventory.items ():
        print ('    {:6d} {}'.format (v, k) )

示例会话:

Thou hast found a chest containing: 13 Gold

Whishest thou to pick up this apparel? [y/*] y


Thy bag now containth:
        13 Gold



Thou hast found a chest containing: 1 Shabby Gloves of Destruction, 1 Surreal Sword, 1 Gleaming Gloves of Constipation, 7 Gold

Whishest thou to pick up this apparel? [y/*] y


Thy bag now containth:
         1 Shabby Gloves of Destruction
         1 Surreal Sword
         1 Gleaming Gloves of Constipation
        20 Gold

正如你所看到的那样,黄金被添加了。此外,如果您发现另一个超级剑,您的库存中将有2个。

答案 1 :(得分:1)

您可以使用字典update()

  

使用其他覆盖的键/值对更新字典   现有密钥。

>>> chest = {}
>>> chest = {"sword": 1, "gold": 5}
>>> inventory = {}
>>> inventory.update(chest)
>>> inventory
{'sword': 1, 'gold': 5}

或者,如果您只需要一个sword项,只需:

>>> inventory['sword'] = chest['sword']
>>> inventory
{'sword': 1}

或者,如果您需要复制多个键(但不是全部):

>>> keys_to_copy = ['sword']
>>> inventory.update(((key, chest[key]) for key in keys_to_copy))
>>> inventory
{'sword': 1}