Lists have the append() function to add an item to the end of the list. Is there a similar function to add to the end of dictionaries? Update() doesn't seem to work.

Example:
>>> a = {'a':'a'}
>>> b = {'b':'b'}
>>> c = {'c':'c'}
>>> a
{'a': 'a'}
>>> b
{'b': 'b'}
>>> c
{'c': 'c'}
>>> a.update(b)
>>> a
{'a': 'a', 'b': 'b'}
>>> a.update(c)
>>> a
{'a': 'a', 'c': 'c', 'b': 'b'}

The end result I'm looking for is {'a':'a','b':'b','c':'c'}. Why did it become {'a': 'a', 'c': 'c', 'b': 'b'} instead?

this is just the way python does it, this doesn't affect you in anyway does it?

Chris

It somewhat does affect me since I was under the assumption that the dictionaries would be in order, it's not too much of a problem since I can work around that. Before I do, is it possible to add items into a dictionary besides using update()?

A dictionaries represents a collection of objects indexed by another collection of immutable key values and are unordered. Method update() would be the easiest way to combine dictionaries, but you can also do it with simple iteration.

for key in dict2:
    dict1[key]=dict2[key]

A dictionaries represents a collection of objects indexed by another collection of immutable key values and are unordered. Method update() would be the easiest way to combine dictionaries, but you can also do it with simple iteration.

for key in dict2:
    dict1[key]=dict2[key]

That seems to only work when key exists in both dict1 and dict2. No matter what I do to try to merge/add items to the dictionary example in the first post, it always ends up being {'a':'a','b':'b','c':'c'}. I will find some other way. Thanks for the help.

That seems to only work when key exists in both dict1 and dict2. No matter what I do to try to merge/add items to the dictionary example in the first post, it always ends up being {'a':'a','b':'b','c':'c'}. I will find some other way. Thanks for the help.

It works as expected:

>>> dd1 = {'a':'a'}
>>> dd2 = {'b':'b', 'c':'c', 'd':'d', 'e':'e'}
>>> for key in dd2:
... 	dd1[key]=dd2[key]
... 	
>>> dd1
{'a': 'a', 'c': 'c', 'b': 'b', 'e': 'e', 'd': 'd'}
>>>

Are you wanting an ordered dictionary? Internet search "python ordered dictionary".

It works as expected:

>>> dd1 = {'a':'a'}
>>> dd2 = {'b':'b', 'c':'c', 'd':'d', 'e':'e'}
>>> for key in dd2:
... 	dd1[key]=dd2[key]
... 	
>>> dd1
{'a': 'a', 'c': 'c', 'b': 'b', 'e': 'e', 'd': 'd'}
>>>

Are you wanting an ordered dictionary? Internet search "python ordered dictionary".

I made a mistake in my previous post but it was too late to fix it. An ordered dictionary, that is exactly what I was looking for. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.