在循环内将项添加到Dictionary

时间:2015-07-02 10:14:55

标签: python dictionary

以下数据来自网页并包含以下条目(如包含多行的表格):

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

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

这是我目前的解决方案:

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

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

4 个答案:

答案 0 :(得分:16)

在您当前的代码中,$(document).delegate('li.child a', 'click', function() { var $this = $(this), $url = $this.attr('href'); window.location = $url; }); 所做的是它更新(更新意味着该值从传入的字典中的相同键的值覆盖)当前字典中的键与传入的字典中的值作为它的参数(添加任何新键:值对,如果存在)。单个平面字典不能满足您的要求,您需要一个字典列表或一个嵌套字典的字典。

如果你想要一个字典列表(列表中的每个元素都是条目的双活元),那么你可以将Dictionary.update()作为一个列表,然后将case_list附加到它(而不是更新)。

示例 -

case

或者您也可以使用字典词典,其中词典中每个元素的键为case_list = [] for entry in entries_list: case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] } case_list.append(case) entry1等,其值为该条目的相应词典。

entry2

答案 1 :(得分:2)

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

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

为此你可以使用每个字典键的列表:

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

答案 2 :(得分:0)

# 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) 

答案 3 :(得分:0)

更简单的解决方案 - 使用 copy() 而不是直接在 dict 中附加 list

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

这不会有任何重复。

相关问题