Python 在循环内将项目添加到字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31181830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:37:20  来源:igfitidea点击:

Adding item to Dictionary within loop

pythondictionary

提问by Kay

Below data is grasped from webpage and containing entries as below(like a table with many rows):

下面的数据是从网页上抓取的,包含如下条目(就像一个多行的表格):

entry1: key1: value1-1, key2: value2-1, key3: value3-1
entry2: key1: value1-2, key2: value2-2, key3: value3-2
entry3: key1: value3-1, key2: value2-3, key3: value3-3
......
entry100: key1: value100-1, key2: value100-2, key3: value100-3

how can I use a dictionary to store this data? the data is from a list thus the 'dictionary append' should be done within a loop...

如何使用字典来存储这些数据?数据来自一个列表,因此“字典附加”应该在一个循环中完成......

here is my current solution:

这是我目前的解决方案:

case_list = {}
for entry in entries_list:
    case = {'key1': value, 'key2': value, 'key3':value }
    case_list.update(case)

but the case_list in the end only contains the last case entry... Can somebody please help me on this? I would expect the case_list containing 100 entries w/o any overwriting among entries, and I will need to store it to DB afterwards.

但最后的 case_list 只包含最后一个案例条目......有人可以帮我吗?我希望包含 100 个条目的 case_list 没有条目之间的任何覆盖,之后我需要将它存储到数据库中。

采纳答案by Anand S Kumar

In your current code, what Dictionary.update()does is that it updates (update means the value is overwritten from the value for same key in passed in dictionary) the keys in current dictionary with the values from the dictionary passed in as the parameter to it (adding any new key:value pairs if existing) . A single flat dictionary does not satisfy your requirement , you either need a list of dictionaries or a dictionary with nested dictionaries.

在您当前的代码中,Dictionary.update()它所做的是更新(更新意味着该值被字典中传递的相同键的值覆盖)当前字典中的键与作为参数传入的字典中的值(添加任何新的键:值对(如果存在)。单个平面字典不能满足您的要求,您需要一个字典列表或一个带有嵌套字典的字典。

If you want a list of dictionaries (where each element in the list would be a diciotnary of a entry) then you can make case_listas a list and then append caseto it (instead of update) .

如果您想要一个字典列表(其中列表中的每个元素都是一个条目的字典),那么您可以制作case_list一个列表,然后附加case到它(而不是更新)。

Example -

例子 -

case_list = []
for entry in entries_list:
    case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }
    case_list.append(case)


Or you can also have a dictionary of dictionaries with the key of each element in the dictionary being entry1or entry2, etc and the value being the corresponding dictionary for that entry.

或者你也可以有一个字典字典,字典中每个元素的键是entry1orentry2等,值是该条目的相应字典。

case_list = {}
for entry in entries_list:
    case = {'key1': value, 'key2': value, 'key3':value }
    case_list[entryname] = case  #you will need to come up with the logic to get the entryname.

回答by Deep Shah

As per my understanding you want data in dictionary as shown below:

根据我的理解,您需要字典中的数据,如下所示:

key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3

for this you can use list for each dictionary keys:

为此,您可以为每个字典键使用列表:

case_list = {}
for entry in entries_list:
    if key in case_list:
        case_list[key1].append(value)
    else:
        case_list[key1] = [value]

回答by Subhasis Patra

# Let's add key:value to a dictionary, the functional way 
# Create your dictionary class 
class my_dictionary(dict): 
    # __init__ function 
    def __init__(self): 
        self = dict()   
    # Function to add key:value 
    def add(self, key, value): 
        self[key] = value 
# Main Function 
dict_obj = my_dictionary() 
limit = int(input("Enter the no of key value pair in a dictionary"))
c=0
while c < limit :   
    dict_obj.key = input("Enter the key: ") 
    dict_obj.value = input("Enter the value: ") 
    dict_obj.add(dict_obj.key, dict_obj.value) 
    c += 1
print(dict_obj)