如何检查if语句中的键值

时间:2017-02-17 04:33:04

标签: python list dictionary for-loop

我希望你们一切顺利。

这就是我的数据的外观:

dictionary1 = {2876: 1, 9212: 1, 953997: 1, 9205: 1, 9206: 1, 9207: 1, 9208: 1, 9209: 1, 9210: 1, 9211: 1, 6908: 1, 1532: 1, 945237: 1, 6532: 2, 6432: 4}

data1 = [[2876, 5423],[2312, 4532],[953997, 5643]...]

我正在尝试运行一个如下所示的语句:

for y in data1:
        if y[0] in dictionary1 and dictionary1[y[0]] == 1:
            dictionary1[y[1]] = 2

据推测,这会创建一个如下所示的新数据集:

dictionary1 = {5423: 2, 953997: 2, 2876: 1, 9212: 1, 953997: 1, 9205: 1, 9206: 1, 9207: 1, 9208: 1, 9209: 1, 9210: 1, 9211: 1, 6908: 1, 1532: 1, 945237: 1, 6532: 2, 6432: 4}

我做错了什么? dictionary1 [y [0]] == 1是检查密钥值的正确方法吗?

谢谢大家。

4 个答案:

答案 0 :(得分:0)

字典理解将列表列表转换为字典:

dict1 =  {t[0]:t[1:] for t in dictionary1}

然后应该很容易做你想做的事情:

for y in data1:
    if y in dict1 and dict1[y] ==1:
        dictionary1[y] = 2

答案 1 :(得分:0)

您可以使用dict.get(key, default)来避免缺失值的异常,并提供安全的默认值。这会将您的循环减少到一个条件:

#!python3
dictionary1 = {2876: 1, 9212: 1, 953997: 1, 9205: 1, 9206: 1, 9207: 1, 9208: 1, 9209: 1, 9210: 1, 9211: 1, 6908: 1, 1532: 1, 945237: 1, 6532: 2, 6432: 4}

data1 = [[2876, 5423],[2312, 4532],[953997, 5643]]

for x,y in data1:
    if dictionary1.get(x, 0) == 1:
        dictionary1[y] = 2

print(dictionary1)

您可以使用dict.update(other)使用单线词典理解来批量覆盖dictionary1中的值:

dictcompr = {b:2 for a,b in data1 if dictionary1.get(a,0) == 1}
dictionary1.update(dictcompr)

然后你可以把它们组合成一个单一的,不圣洁的,不可维护的,几乎不可读的混乱:

dictionary1.update({b:2 for a,b in data1 if dictionary1.get(a,0) == 1})

<强>更新

要删除值为1的所有键,您可以选择:

for k,v in dictionary1.items():
    if v == 1:
        del dictionary1[k]

# Versus:

d2 = dict(filter(lambda item: item[1] != 1, dictionary1.items()))
dictionary1 = d2

# or

dictionary1.clear()
dictionary1.update(d2)

坦率地说,为了您的目的,for循环可能更好。 filter方法可以将lambda作为参数,以配置过滤的内容。如果您希望多次引用字典,则使用clear()/update()是一个胜利。也就是A = B = dictionary1。在这种情况下,clear/update将保留相同的底层对象,因此链接仍然成立。 (对于for循环也是如此 - 该优势仅适用于需要临时的filter。)

答案 2 :(得分:0)

请试试这个,

    for y in data1:
    if y[0] in dictionary1.keys() and dictionary1.keys() == y[0]:
        dictionary1[y[1]] = 2

答案 3 :(得分:-1)

你可以简单地使用

for y in data1:
        if dictionary1.has_key(y[0]):
            dictionary1[y[1]] = 2

希望这就是你要找的东西。

相关问题