Is there a method like append for dictionaries
Question: How do i add key,value to a dictionary in python? I defined an empty
dictionary and now I want to pass a bunch of keys from a list and set their
value as 1. From what I did it creates me every iteration a new dictionary,
but I want to append the key,value so eventually I will recieve only one
dictionary. this is my code:

    
    
    def count_d(words):
        count_dict={} 
        words_set= set(words)
        for i in words_set:
            count_dict[i]= 1
            print (count_dict)
    


Answer: What you are looking for is
[dict.fromkeys](http://docs.python.org/2/library/stdtypes.html#dict.fromkeys)
along with
[dict.update](http://docs.python.org/2/library/stdtypes.html#dict.update).

**From the docs**

> Create a new dictionary with keys from seq and values set to value.

**Example Usage**

    
    
    >>> d = {}
    >>> d.update(dict.fromkeys(range(10), 1))
    >>> d
    {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1}
    

Note, you need an `dict.update` along with `dict.fromkeys`, so as to update
the dictionary in-place

Instead, if you want to create a dictionary and assign use the notation

    
    
    >>> d = dict.fromkeys(range(10), 1)
    >>> d
    {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1}  
    

Unfortunately, for in-place update, you need to create a throw-away dictionary
before passing to the `dict.update` method. A non-intuitive method is to
leverage [itertools](http://docs.python.org/2/library/itertools.html)

    
    
    from itertools import izip, repeat
    d.update(izip(xrange(10), repeat(1)))
    

The same idea can be extended to
[OrderedDict](http://docs.python.org/2/library/collections.html#collections.OrderedDict)
which is often used, as an alternate for `OrderedSet` as standard library does
not provide one.

