如何创建一个字典来存储我替换的值而不导入defaultdic?

时间:2017-04-20 18:32:49

标签: python python-3.x dictionary

我正在尝试创建一个函数,将我的字典列表中的值替换为整数。我所做的功能是替换值,但不存储替换值

sample=[{1: 'A', 2: 'A', 3: 'C', 4: 'A', 5: 'C'}, {1: 'A', 2: 'G', 3: 'A', 
4: 'C', 5: 'A'}, {1: 'A', 2: 'C', 3: 'T', 4: 'A', 5: 'A'}]
def updatevaluedict(dictionary,va):
'''takes in a dictionary and replaces the values that you
    want with ones'''
emptydict2=[]
for individual_dict in dictionary:
    for key in individual_dict: 
        if individual_dict[key] ==va:
            individual_dict[key]=1###LOOK HERE
        else:
            individual_dict[key]=0
return dictionary

这会打印出我想要的值

print(updatevaluedict(sample,'A')

我试图用' 1&替换我想要的值,其余用' 0' s。 但是,实际字典中的所有值都已替换为0

3 个答案:

答案 0 :(得分:0)

这将修改现有字典,不确定您要尝试实现的内容,因此将所有值替换为数字1

sample=[{1: 'A', 2: 'A', 3: 'C', 4: 'A', 5: 'C'}, {1: 'A', 2: 'G', 3: 'A', 
4: 'C', 5: 'A'}, {1: 'A', 2: 'C', 3: 'T', 4: 'A', 5: 'A'}]
for dct in sample:
    for k in dct:
        dct [k] = 1
print (sample)

打印(在一行上):

[{1: 1, 2: 1, 3: 1, 4: 1, 5: 1}, 
{1: 1, 2: 1, 3: 1, 4: 1, 5: 1}, 
{1: 1, 2: 1, 3: 1, 4: 1, 5: 1}]

或者将其中一个词典传递给函数并修改它,您可以使用列表索引,如:

sample[0]

如下所示(这也让你选择用字母值替换哪个整数,通过更改"数字"变量):

def replace(dct,number):
    for k in dct:
        dct [k] = number
    return dct

number = 2
sample[0] = replace(sample[0],number)
print (sample)

打印(在一行上):

[{1: 2, 2: 2, 3: 2, 4: 2, 5: 2}, 
{1: 'A', 2: 'G', 3: 'A', 4: 'C', 5: 'A'}, 
{1: 'A', 2: 'C', 3: 'T', 4: 'A', 5: 'A'}]

答案 1 :(得分:0)

sample=[{1: 'A', 2: 'A', 3: 'C', 4: 'A', 5: 'C'}, {1: 'A', 2: 'G', 3: 'A', 
         4: 'C', 5: 'A'}, {1: 'A', 2: 'C', 3: 'T', 4: 'A', 5: 'A''}]

def updatevaluedict(individual_dict, va):
    '''
    takes in a dictionary and replaces the values that you
    want with ones
    '''
    for key in individual_dict: 
        if individual_dict[key] == va:
            individual_dict[key] = 1###LOOK HERE
        else:
            individual_dict[key] = 0
     return dictionary

def update_list(ll=[]):
    # update list of dictionary
    new_ll = []
    for each_dict in ll:
        new_ll.append(updatevaluedict(each_dict, va))
    return new_ll

答案 2 :(得分:0)

通过运行代码,我注意到您在上一个字典的末尾有一个额外的title'

除了你的代码运行得很好,使用python 2.7.12