0

I have the following code:

list1 = ['a', 'b', 'c']
dict1 = {}

for item in list1:
   dict1.update({"letter": item})

print(dict1)

I want to iterate over the list and add each element into the dictionary with the same key for each element. So in this case, the required output should be:

{'letter': 'a', 'letter': 'b', 'letter': 'c'}

But the output I get is:

{'letter': 'c'}

Only the last element is added to the dict. How can I get the required output?

Thanks in advance.

The6thSense
  • 8,103
  • 8
  • 31
  • 65
modarwish
  • 495
  • 10
  • 22
  • 12
    dictonary can not have duplicate key – The6thSense Jul 09 '15 at 19:14
  • 3
    you sure you dont want `{'a':'letter','b':'letter','c':'letter'}` ? since that is possible ... – Joran Beasley Jul 09 '15 at 19:16
  • 2
    If you want multiple items per key, give each key a list of values rather than an atomic value. – Jacques de Hooge Jul 09 '15 at 19:16
  • What about a list of unique dictionaries, like so: [{"letter": "a"}, {"letter": "b"}, {"letter": "c"}] @vignesh Kalai – modarwish Jul 09 '15 at 19:17
  • You could certainly do that, but you shouldn't want to. – TigerhawkT3 Jul 09 '15 at 19:20
  • I am working on implementing the NB classifier using NLTK like [here](http://www.nltk.org/howto/classify.html). The features are taken as a list of tuples; within each tuple, there is a dictionary and a string to represent the class label.The dictionaries seem to have the same keys.. @TigerhawkT3 – modarwish Jul 09 '15 at 19:22
  • http://stackoverflow.com/questions/960733/python-creating-a-dictionary-of-lists – Constantin Jul 09 '15 at 19:23
  • You might want to use the dictionary initiated list. Then the key will store a list of values. You can use defaultdict from collections. – sweet_sugar Jul 09 '15 at 19:34

1 Answers1

0
sa=[{"letter":a} for in list1]
sa
[{"letter":a},{"letter":b},{"letter":c}]

But there is no need to do this though

The right method would be to add a list to the key letter

dict1={"letter":[]}
dict1["letter"].extend([a for a in list1])
dict
{"letter":["a","b","c"]}
The6thSense
  • 8,103
  • 8
  • 31
  • 65
  • This is almost certainly solving [Problem Y](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – TigerhawkT3 Jul 09 '15 at 19:21
  • What's the benefit of showing the output of an unnecessary operation? – TigerhawkT3 Jul 09 '15 at 19:25
  • I don't understand how it's an answer in the slightest, but it looks like you've helped someone solve his [Problem Y](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem), so whatever. – TigerhawkT3 Jul 09 '15 at 19:31
  • Thanks for the help. Experimentation is never wrong. @Vignesh Kalai – modarwish Jul 09 '15 at 19:35