如果此值不存在于字典中,请添加值

时间:2016-06-13 14:56:53

标签: python python-2.7

我有一个默认字典。我循环遍历许多字符串并将它们作为数字添加到键下的目录中,但前提是字典中没有该值。所以我的代码看起来像这样:

from collections import defaultdict
strings = ["val1", "val2", "val2", "val3"]
my_dict = defaultdict(list)

key = 0
for string in strings:
    if string not in my_dict.itervalues():
        my_dict[key].append(string)
        key += 1

print my_dict

但它似乎不起作用,因为所有字符串都添加到字典中,如下所示:

defaultdict(<type 'list'>, {0: ['val1'], 1: ['val2'], 2: ['val2'], 3: ['val3']})

&#39; val2的&#39;不应该添加,它应该是这样的:

defaultdict(<type 'list'>, {0: ['val1'], 1: ['val2'], 2: ['val3']})

我做错了什么?

1 个答案:

答案 0 :(得分:2)

请注意,my_dict.itervalues()会返回您的案例中的列表列表。因此,string not in lists始终返回True,您可以从以下代码中看到,

>>> "val2" not in [["val1"], ["val2"]]
True

要获得所需的结果,请使用itertools.chain.from_iterable

将列表列表展平到列表中
>>> import itertools
>>> "val2" not in itertools.chain.from_iterable([["val1"], ["val2"]])
False

您案例的完整源代码,

from collections import defaultdict
import itertools

strings = ["val1", "val2", "val2", "val3"]
my_dict = defaultdict(list)

key = 0
for string in strings:
    if string not in itertools.chain.from_iterable(my_dict.values()): # flat a list of lists into a list
        my_dict[key].append(string)
        key += 1

print(my_dict)
# Output
defaultdict(<type 'list'>, {0: ['val1'], 1: ['val2'], 2: ['val3']})