Ason
Ason

Reputation: 509

Dictionary into dictionary in python

Ok, this one should be simple. I have 3 dictionaries. They are all made, ordered, and filled to my satisfaction but I would like to put them all in an overarching dictionary so I can reference and manipulate them more easily and efficiently.

Layer0 = {}
Layer1 = {}
Layer2 = {}

here they are when created, and afterwards I feebly tried different things based on SO questions:

Layers = {Layer0, Layer1, Layer2}

which raised a syntax error

Layers = {'Layer0', 'Layer1', 'Layer2'}

which raised another syntax error

(Layers is the Dictionary I'm trying to create that will have all the previously made dictionaries within it)

All the other examples I found on SO have been related to creating dictionaries within dictionaries in order to fill them (or filling them simultaneously) and since I already coded a large number of lines to make these dictionaries, I'd rather put them into a dictionary after the fact instead of re-writing code.

It would be best if the order of the dictionaries are preserved when put into Layers

Does anyone know if this is possible and how I should do it?

Upvotes: 2

Views: 190

Answers (2)

A Kaptur
A Kaptur

Reputation: 307

Keep in mind that dictionaries don't have an order, since a dictionary is a hash table (i.e. a mapping from your key names to a unique hash value). Using .keys() or .values() generates a list, which does have an order, but the dictionary itself doesn't.

So when you say "It would be best if the order of the dictionaries are preserved when put into Layers" - this doesn't really mean anything. For example, if you rename your dictionaries from "Layer1, Layer2, Layer3" to "A, B, C," you'll see that Layers.keys() prints in the order "A, C, B." This is true regardless of the order you used when building the dictionary. All this shows is that the hash value of "C" is less than that of "B," and it doesn't tell you anything about the structure of your dictionary.

This is also why you can't directly iterate over a dictionary (you have to iterate over e.g. a list of the keys).

As a side note, this hash function is what allows a dictionary to do crazy fast lookups. A good hash function will give you constant time [O(1)] lookup, meaning you can check if a given item is in your dictionary in the same amount of time whether the dictionary contains ten items or ten million. Pretty cool.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

Dictionary items have both a key and a value.

Layers = {'Layer0': Layer0, 'Layer1': Layer1, 'Layer2': Layer2}

Upvotes: 10

Related Questions