【问题标题】:How to add list elements into dictionary如何将列表元素添加到字典中
【发布时间】:2015-05-13 07:12:41
【问题描述】:

假设我有 dict = {'a': 1, 'b': 2'} 并且我还有一个列表 = ['a', 'b, 'c', 'd', 'e'] .目标是将列表元素添加到字典中,并打印出新的 dict 值以及这些值的总和。应该是这样的:

2 a
3 b
1 c
1 d
1 e
Total number of items: 8

相反,我得到:

1 a
2 b
1 c
1 d
1 e
Total number of items: 6

到目前为止我所拥有的:

def addToInventory(inventory, addedItems)
    for items in list():
        dict.setdefault(item, [])

def displayInventory(inventory):
    print('Inventory:')
    item_count = 0
    for k, v in inventory.items():
       print(str(v) + ' ' + k)
       item_count += int(v)
    print('Total number of items: ' + str(item_count))

newInventory=addToInventory(dict, list)
displayInventory(dict)

任何帮助将不胜感激!

【问题讨论】:

  • for items in list(): dict.setdefault(item, []) 这根本没有意义。
  • 如何让 b 为 2?您在哪里进行实际添加?
  • @TimCastelijns - 这就是问题所在。它没有从列表中添加“a”或“b”,而是保留了 dict 的原始值。
  • @thefourtheye - 最后有一个 .append() ,但它给出了一个关于 int 没有方法 .append 的错误,所以我把它拿出来了。还在学习!

标签: python list python-3.x dictionary


【解决方案1】:

如果键已经存在,您只需迭代列表并根据键增加计数,否则将其设置为 1。

>>> d = {'a': 1, 'b': 2}
>>> l = ['a', 'b', 'c', 'd', 'e']
>>> for item in l:
...     if item in d:
...         d[item] += 1
...     else:
...         d[item] = 1
>>> d
{'a': 2, 'c': 1, 'b': 3, 'e': 1, 'd': 1}

你可以用dict.get写同样的,简洁的,像这样

>>> d = {'a': 1, 'b': 2}
>>> l = ['a', 'b', 'c', 'd', 'e']
>>> for item in l:
...     d[item] = d.get(item, 0) + 1
>>> d
{'a': 2, 'c': 1, 'b': 3, 'e': 1, 'd': 1}

dict.get函数会寻找key,如果找到则返回值,否则返回第二个参数传入的值。如果item 已经是字典的一部分,那么将返回对应它的数字,我们将1 添加到它并将其存储回相同的item。如果没有找到,我们将得到 0(第二个参数),然后我们将其加 1 并存储在 item 中。


现在,要获得总数,您可以使用sum 函数将字典中的所有值相加,就像这样

>>> sum(d.values())
8

dict.values 函数将返回字典中所有值的视图。在我们的例子中,它将编号,我们只需使用 sum 函数将它们全部添加。

【讨论】:

    【解决方案2】:

    另一种方式:

    使用集合模块:

    >>> import collections
    >>> a = {"a": 10}
    >>> b = ["a", "b", "a", "1"]
    >>> c = collections.Counter(b) + collections.Counter(a)
    >>> c
    Counter({'a': 12, '1': 1, 'b': 1})
    >>> sum(c.values())
    14
    

    【讨论】:

      【解决方案3】:

      如果您正在使用 Python 自动化无聊的东西中的 List to Dictionary Function for Fantasy Game Inventory 寻找解决方案,下面是一个有效的代码:

      # inventory.py
      stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
      
      #this part of the code displays your current inventory
      def displayInventory(inventory): 
          print('Inventory:')
          item_total = 0
      
          for k, v in inventory.items():
              print(str(v) + ' ' + k)
              item_total += v
          print("Total number of items: " + str(item_total))
      
      #this launches the function that displays your inventory
      displayInventory(stuff) 
      
      dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
      
      # this part is the function that adds the loot to the inventory
      def addToInventory (inventory, addedItems): 
      
          print('Your inventory now has:')
      
      #Does the dict has the item? If yes, add plus one, the default being 0
          for item in addedItems:
              stuff[item] = stuff.get(item, 0) + 1 
      
      
      # calls the function to add the loot
      addToInventory(stuff, dragonLoot) 
      # calls the function that shows your new inventory
      displayInventory(stuff) 
      

      【讨论】:

      • 在寻找这个精确练习的解决方案时,这是谷歌的第一个结果,因此我在这里发布了本书所要求的解决方案。我不得不从其他答案中学习并进行一些调整。
      【解决方案4】:

      关于“幻想游戏清单的字典函数列表”的问题 - 第 5 章。使用 Python 自动化无聊的东西。

      # This is an illustration of the dictionaries
      
      # This statement is just an example inventory in the form of a dictionary
      inv = {'gold coin': 42, 'rope': 1}
      # This statement is an example of a loot in the form of a list
      dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
      
      # This function will add each item of the list into the dictionary
      def add_to_inventory(inventory, dragon_loot):
      
          for loot in dragon_loot:
              inventory.setdefault(loot, 0) # If the item in the list is not in the dictionary, then add it as a key to the dictionary - with a value of 0
              inventory[loot] = inventory[loot] + 1 # Increment the value of the key by 1
      
          return inventory
      
      # This function will display the dictionary in the prescribed format
      def display_inventory(inventory):
      
          print('Inventory:')
          total_items = 0
      
          for k, v in inventory.items():
              print(str(v) + ' ' + k)
              total_items = total_items + 1
      
          print('Total number of items: ' + str(total_items))
      
      # This function call is to add the items in the loot to the inventory
      inv = add_to_inventory(inv, dragon_loot)
      
      # This function call will display the modified dictionary in the prescribed format
      display_inventory(inv)
      

      【讨论】:

        【解决方案5】:

        使用collections.Counter,因为它拥有您手头任务所需的一切:

        from collections import Counter
        
        the_list = ['a', 'b', 'c', 'd', 'e']
        
        counter = Counter({'a': 1, 'b': 2})
        counter.update(the_list)
        
        for c in sorted(counter):
            print c, counter[c]
        

        为了获得总数,您可以简单地将 counter 的值相加:

        sum(counter.values())
        # 8
        

        【讨论】:

          【解决方案6】:
          stuff={'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}
          dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
          
          def displayInventory(inventory):
              print('Inventory:')
              item_total=0
              for k,v in inventory.items():
                  print(str(v)+' '+k)
                  item_total=item_total+v
              print('Total number of items: '+ str(item_total))
          
          def addToInventory(inventory,addedItems):
              for v in addedItems:
                  if v in inventory.keys():
                      inventory[v]+=1
                  else:
                      inventory[v]=1
          
          addToInventory(stuff,dragonLoot)    
          
          displayInventory(stuff)
          

          【讨论】:

          • 请解释您的代码,否则无济于事。
          【解决方案7】:
          invent = {'rope': 1, 'torch':6, 'gold coin': 42, 'dagger':1, 'arrow':12}
          dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
          
          def displayInventory(weapons):
              print('Inventory')
              total = 0
              for k, v in weapons.items():
                  print(str(v), k)
                  total += v
              print('Total number of items: ' + str(total))
          
          def addToInventory(inventory, addedItems):
              for item in addedItems:
                  inventory.setdefault(item, 0)
                  inventory[item] = inventory[item] + 1
              return(inventory)
          
          
          
          displayInventory(addToInventory(invent, dragonLoot))
          

          【讨论】:

            【解决方案8】:

            对于您问题的第一部分,要将列表项添加到字典中,我使用了以下代码:

            inventory = {'gold coin': 42, 'rope': 1}
            dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
            
            def addToInventory(inventory, addedItems):
                for i in addedItems:
                    if i in inventory:
                        inventory[i] = inventory[i] + 1
                    else:
                        inventory[i] = 1 #if the item i is not in inventory, this adds it
                                         #   and gives the value 1.
            
            
            
            

            我之所以分享它,是因为我在 .get 函数中使用了 if 语句,就像其他 cmets 一样。现在我学习了.get,它似乎比我的代码更简单、更短。但是在我遇到这个练习的“自动化无聊的东西”一书的章节中,我还没有学习(或者说不够好).get 函数。

            至于显示库存的功能,我和其他cmets的代码是一样的:

            def displayInventory(inventory):
                print('Inventory:')
                tItems = 0 
                for k, v in inventory.items(): 
                    print(str(v) + ' ' + k)
                for v in inventory.values():
                    tItems += v
                print()
                print('Total of number of items: ' + str(tItems))
            

            我调用了这两个函数,结果如下:

            >>> addToInventory(inventory, dragonLoot)
            >>> displayInventory(inventory)
            
            Inventory:
            45 gold coin
            1 rope
            1 dagger
            1 ruby
            
            Total of number of items: 48
            
            

            我希望这会有所帮助。

            【讨论】:

              【解决方案9】:
              def addToInventory(inventory, addedItems):
                  for v in addedItems:
                      if v in inventory.keys():
                          inventory[v] += 1
                      else:
                          inventory[v] = 1
                  return inventory
              
              inv = {'gold coin': 42, 'rope': 1}
              dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
              inv = addToInventory(inv, dragonLoot)
              displayInventory(inv)
              

              【讨论】:

                【解决方案10】:

                对于这个问题的第一部分,这是我想出的代码。

                invt = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
                print ("Inventory:")
                total = sum(invt.values())
                for x, v in invt.items():
                  print (str(v) + ' ' + x)
                print ("Total number of items: {}".format(total))
                

                我看到大多数人都在通过循环进行交互以添加到总变量中。但是使用 sum 方法,我跳过了一步..

                随时接受反馈....

                【讨论】:

                  【解决方案11】:

                  以下是使用上述技巧的代码,加上名词复数的细微变化。对于那些愿意和勇敢的人来说,有 ifs 和 elifs 的任务来处理异常;)

                  # sets your dictionary
                  backpack = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
                  
                  # this function display your current inventory
                  def displayInventory(inventory):
                      print("Backpack:")
                      itemTotal = 0
                      for k, v in inventory.items():
                  
                      # creates a simple plural version of the noun 
                      # (adds only the letter "s" at the end of the word) does not include exceptions 
                      # (for example, torch - 'torchs' (should be 'torches'), etc.
                          if v > 1:
                              print(str(v) + ' ' + k +'s')
                          else:
                              print(str(v) + ' ' + k)
                  
                          itemTotal += v
                      print("Total quantity of items: " + str(itemTotal))
                  
                  # sets your loot 
                  dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
                  
                  # this function adds your loot to your inventory
                  def addToInventory(inventory, addedItems):
                      for item in addedItems:
                          inventory[item] = inventory.get(item,0) + 1
                  
                  # launch your functions
                  addToInventory(backpack, dragonLoot)
                  displayInventory(backpack)
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 2020-09-18
                    • 1970-01-01
                    • 2013-01-31
                    • 2019-08-23
                    • 2011-03-22
                    • 2023-01-22
                    • 1970-01-01
                    相关资源
                    最近更新 更多