GVKun编程网logo

在Python中将新项目添加到字典中(在python中将新项目添加到字典中)

26

在本文中,我们将详细介绍在Python中将新项目添加到字典中的各个方面,并为您提供关于在python中将新项目添加到字典中的相关解答,同时,我们也将为您带来关于ES是否支持将新项目添加到现有文档的嵌套

在本文中,我们将详细介绍在Python中将新项目添加到字典中的各个方面,并为您提供关于在python中将新项目添加到字典中的相关解答,同时,我们也将为您带来关于ES是否支持将新项目添加到现有文档的嵌套字段中?、Python for循环附加到字典中的每个键、Python函数:遍历一个列表并将列表中每次出现的内容添加到字典中、python实践项目三:将列表添加到字典的有用知识。

本文目录一览:

在Python中将新项目添加到字典中(在python中将新项目添加到字典中)

在Python中将新项目添加到字典中(在python中将新项目添加到字典中)

我想将一个项目添加到Python中的现有字典中。例如,这是我的字典:

default_data = {            ''item1'': 1,            ''item2'': 2,}

我想添加一个新项目,例如:

default_data = default_data + {''item3'':3}

我该如何实现?

答案1

小编典典

default_data[‘item3’] = 3

像py一样容易。

另一个可能的解决方案:

default_data.update({''item3'': 3})

如果您想一次插入多个项目,这很好。

ES是否支持将新项目添加到现有文档的嵌套字段中?

ES是否支持将新项目添加到现有文档的嵌套字段中?

我有这样的ES文档。

{  "title": "Nest eggs",  "comments": [ {  "name":    "John Smith",  "comment": "Great article",},{  "name":    "Alice White",  "comment": "More like this please",}]}

现在我想在此文档中添加一个新的“注释”,最后该文档将是

{   "title": "Nest eggs",   "comments": [ {  "name":    "John Smith",  "comment": "Great article",},{  "name":    "Alice White",  "comment": "More like this please",},{  "name":    "New guy",  "comment": "something here",}]}

我不想在每次追加过程中都提供现有的“ comments”对象,因此最好是每次向此嵌套字段添加新对象的最佳方法。

我的解决方案:

 POST test_v2/_update/Z_nM_2wBjkGOA-r6ArOb {  "script": {  "lang": "painless",  "inline": "ctx._source.nested_field.add(params.object)",  "params": {     "object": {        "model" : "tata nano",        "value" : "2"     }  } }}

答案1

小编典典

检查脚本本身中的空字段。如果该字段不存在,则首先创建

 POST test3/_update/30RaAG0BY3127H1HaOEv{  "script": {    "lang": "painless",    "inline": "if(!ctx._source.containsKey(''comments'')){ctx._source[''comments'']=[]}ctx._source.comments.add(params.object)",    "params": {      "object": {        "model": "tata nano",        "value": "2"      }    }  }}

Python for循环附加到字典中的每个键

Python for循环附加到字典中的每个键

我正在迭代一个元组列表和一个字符串列表.字符串是列表中项目的标识符.我有一个字典,其字符串标识符为键,并且每个值都有一个最初为空的列表.我想从元组列表中向每个键添加一些内容.我正在做的简化版本是:

tupleList = [("A","a"),("B","b")]
stringList = ["Alpha","Beta"]
dictionary = dict.fromkeys(stringList,[])  # dictionary = {'Alpha': [],'Beta': []}
for (uppercase,lowercase),string in zip(tupleList,stringList):
    dictionary[string].append(lowercase)

我希望这能给出dictionary = {‘Alpha’:[‘a’],’Beta’:[‘b’]},但我发现{‘Alpha’:[‘a’,’b’],‘Beta’:[‘a’,’b’]}.有谁知道我做错了什么?

解决方法

您的问题是您通过引用共享两个键之间的列表.

会发生什么是dict.fromkeys没有为每个键创建一个新列表,但是为所有键提供了相同列表的引用.你的其余代码看起来正确:)

而不是这样做你应该使用defaultdict,基本上它是一个dict,如果它们不存在就会创建新值,如果它们存在则检索它们(并且在插入项目时不需要if / else来检查是否它已经存在).它在这种情况下非常有用:

from collections import defaultdict

tupleList = [("A","Beta"]
dictionary = defaultdict(list) # Changed line
for (uppercase,stringList):
    dictionary[string].append(lowercase)

Python函数:遍历一个列表并将列表中每次出现的内容添加到字典中

Python函数:遍历一个列表并将列表中每次出现的内容添加到字典中

一旦您从战利品中添加了单个项目,您就会return,因此不允许您遍历列表 loot

这应该可以解决问题:

def add_inv(inven,loot):
    inven = dict(inven)
    for list_item in loot:
        inven.setdefault(list_item,0)
        inven[list_item] = inven[list_item] + 1

    return inven


treasure = ['gold coin','dagger','gold coin','ruby']
treasure_inv = {'gold coin': 42,'rope': 1}
print(add_inv(treasure_inv,treasure))
,

这是:

def add_inv(inven,loot):
    inven = dict(inven)
    for list_item in loot:
        if list_item not in inven:
            inven[list_item] = 1
        else:
            inven[list_item] += 1
    return inven

treasure = ['gold coin','ruby' ]
treasure_inv = {'gold coin': 42,treasure))

#{'gold coin': 45,'rope': 1,'dagger': 1,'ruby': 1}

python实践项目三:将列表添加到字典

python实践项目三:将列表添加到字典

1、创建一个字典,其中键是字符串,描述一个物品,值是一个整型值,说明有多少该物品。例如,字典值{''rope'': 1, ''torch'': 6, ''gold coin'': 42, ''dagger'': 1, ''arrow'': 12}意味着有 1 条绳索、 6 个火把、 42 枚金币等。

2、写一个名为 displayInventory()的函数,显示出字典中所有物品及其数量,并统计出总数量

3、写一个名为 addToInventory(inventory, addedItems)的函数, 其中 inventory 参数是一个字典, 存储物品清单, addedItems 参数是一个列表,存储需要更新的物品。addToInventory()函数应该返回一个字典,表示更新过后的物品清单。

代码一:

 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3 #打印字典
 4 def displayInventory(inventory):
 5     print ''Inventory:''
 6     item_total=0
 7     for k,v in inventory.items():
 8         print str(v)+'' ''+k
 9         item_total+=v
10     print ''Total number of items:''+str(item_total)
11 #列表添加到字典
12 def addToInventory(inventory,addItems):
13     for k in addItems:
14         if k in inventory.keys():
15             inventory[k]+=1
16         else:
17             inventory[k]=1
18     return  inventory
19 
20 #初始字典
21 inv={''gold coin'':42,''rope'':1}
22 #需要添加的列表
23 dragonLoot=[''gold coin'',''dagger'',''gold coin'',''gold coin'',''ruby'']
24 #将列表添加到字典
25 inv=addToInventory(inv,dragonLoot)
26 #显示更新后的字典
27 displayInventory(inv)

显示结果:

 代码二(实现同样功能):

 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3 def displayInventory(inven):
 4     print "Inventory:"
 5     item_total=0
 6     for k,v in inven.items():
 7         print str(v)+" "+k
 8         item_total+=v
 9     print "Total number of the items: "+str(item_total)
10 
11 def addListToInventory(inven,addedItems):
12     for i in range(len(addedItems)):
13         if addedItems[i] in inven.keys():
14             inven[addedItems[i]]+=1
15         else:
16             inven.setdefault(addedItems[i],1)
17     return inv
18 inv={''gold coin'':42,''rope'':1}
19 addedList=[''gold coin'',''dagger'',''gold coin'',''gold coin'',''ruby'']
20 inv=addListToInventory(inv,addedList)
21 displayInventory(inv)

运行结果:

 

关于在Python中将新项目添加到字典中在python中将新项目添加到字典中的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于ES是否支持将新项目添加到现有文档的嵌套字段中?、Python for循环附加到字典中的每个键、Python函数:遍历一个列表并将列表中每次出现的内容添加到字典中、python实践项目三:将列表添加到字典的相关知识,请在本站寻找。

本文标签: