0

I'm trying to make a list of dictionaries in python with every letter of a word in each dict. This is my code:

words = ["bella","label","roller"]
list1 = [{}] * len(words)

for i in range(len(words)):
    for letter in words[i]:
        list1[i][letter] = 0

print(list1)

And this is my output:

[{'b': 0, 'e': 0, 'l': 0, 'a': 0, 'r': 0, 'o': 0},
 {'b': 0, 'e': 0, 'l': 0, 'a': 0, 'r': 0, 'o': 0},
 {'b': 0, 'e': 0, 'l': 0, 'a': 0, 'r': 0, 'o': 0}]

Why don't I have a different dictionary for every word?

Cubix48
  • 2,607
  • 2
  • 5
  • 17
StevieG25
  • 39
  • 4
  • *with every letter of a word in each dict* -- so why your code has numbers? – Lei Yang Mar 30 '22 at 15:45
  • 2
    Try `list1 = [{} for _ in words]` instead. – j1-lee Mar 30 '22 at 15:45
  • @Lei Yang I'm trying to count the letters but I'm stuck before I got to that – StevieG25 Mar 30 '22 at 15:47
  • 1
    It would be helpful if you demonstrated your _expected_ output. – Chris Mar 30 '22 at 15:48
  • Sorry for the confusion, I'm trying to find common characters in each word, but first I tried to make a dictionary for each word – StevieG25 Mar 30 '22 at 15:52
  • @StevieG25 if you want the common characters between these words without the number of occurrences, you can use ``set.intersection(*[set(word) for word in words])``. – Cubix48 Mar 30 '22 at 15:59
  • 2
    j1 has the answer to your question. As to why your approach doesn't work...`[{}] * len(words)` first creates a list containing a dictionary, and then the repetition operator (`*`) makes copies of that list and merges them together. The repetition operator does a **shallow copy**, and so each of the created lists references the same map as its single value. So you end up with a list of references to the same dictionary. Using `[{} for _ in words]` gives you what you want because it's essentially a `for` loop, and so the `{}` is evaluated multiple times, each time creating a unique dictionary. – CryptoFool Mar 30 '22 at 16:02

1 Answers1

1

Just use collections.Counter.

from collections import Counter

words = ["bella", "label", "roller"]
letter_counts = [dict(Counter(word)) for word in words]
print(letter_counts)

output

[{'b': 1, 'e': 1, 'l': 2, 'a': 1}, {'l': 2, 'a': 1, 'b': 1, 'e': 1}, {'r': 2, 'o': 1, 'l': 2, 'e': 1}]

update

Your code doesn't work because [{}] * len(words) makes a list with items(dict) that have same reference. Updating the dict will affect all items in list. Just try this code

lst = [{}] * 2
lst[0]['a'] = 2
lst[1]['a'] = 3
print(lst)
# [{'a': 3}, {'a': 3}]
Lei Yang
  • 3,970
  • 6
  • 38
  • 59