I'm creating a dictionary using the dict(zip(..))
method, but I'm finding when appending its values i get differing results to appending a dictionary created in the default x = {key: value}
or dict([key, value], ..)
way..
Heres my example - i have a list of dictionaries:
my_values = [{"a": "blue", "b": "red"}, {"c": "blue", "d": "red"}]
I find the common colours from this list:
for item in my_values:
data = []
data.append(set(item.values()))
common_colors = data[0]
for item in data[1:]:
common_colors &= item
And create a dictionary using zip from these common colors:
colors_a = dict(zip(common_colors, [
[]] * len(common_colors)))
If i append to this dictionary created via zip method:
# Colors A
for item in my_values:
for key, value in item.iteritems():
if value in colors_a:
colors_a[value].append(key)
I get odd results:
print colors_a
# {'blue': ['a', 'b', 'c', 'd'], 'red': ['a', 'b', 'c', 'd']}
When compared to if i create the dictionary using standard way:
colors_b = {"red": [], "blue": []}
And append to it:
# Colors B
for item in my_values:
for key, value in item.iteritems():
if value in colors_b:
colors_b[value].append(key)
I get the correct results:
print colors_b
# {'blue': ['a', 'c'], 'red': ['b', 'd']}
Even though before being appended the dictionaries are identical:
colors_a = dict(zip(common_colors, [
[]] * len(common_colors)))
colors_b = {"red": [], "blue": []}
print colors_a == colors_b
# True
Any know any clues to what going on is much appreciated!