Newbie Dictionary Question
Quinn Dunkan
quinn at riyal.ugcs.caltech.edu
Sat Mar 31 13:13:30 EST 2001
On Sat, 31 Mar 2001 14:57:19 GMT, Gary Walker <borealis3 at home.com> wrote:
>I *think* I want to do the following:
>
>I want to create a list (this I'm able to do)
>Then I want to dynamically create a dictionary for each item in the list,
>add some keys (and values), and then put the dictionary in the list.
>
>(This part is frustrating me, because my newbie python code is referencing
>the SAME dictionary for each of the list indexes, this NOT what I want. I
>want a new instance of a dictionary for each pass thru the list as I loop)
list = []
for elt in thingsies:
list.append({'key': elt})
>I want to do this because this way I can have an ordered list of key/value
>pairs... at least that was my plan...
Well, then a dictionary isn't going to help you, it's not ordered. You might
want a list of pairs:
a = [
('foo', 'a'),
('bar', 'q'),
('baz', 'j'),
('faz', 't'),
]
Or, if you mean 'sorted' when you say 'ordered', you could sort a dictionary's
keys and iterate over that:
d = { ... }
ks = d.keys()
ks.sort()
for k in ks:
print d[k]
>In other words:
>How do I dynamically create a dictionary whose name is not known until
>runtime?
Use braces:
{'foo': bar}
Nitpick: dictionaries don't have names. No objects have names. Dictionaries
might be bound to one, two, three, a million, or zero names, but they
themselves don't have names. So "{'foo': bar}" creates a dictionary without a
name. "d = {'foo': bar}" creates a dictionary without a name *and* a name
in the current environment (global or local) that refers to that dictionary.
"def f(x): ..." creates a function without a name and a name in the current
environment that refers to that function. "a = b = {}" creates a function
without a name, and two names in the current environment that refer to it.
"a[0] = {}" creates a dictionary without a name and asks 'a' to store a
reference to it in its 0th element.
>Actually, they don't have to be ordered, so I suppose (thinking aloud here)
>that I could use a dictionary of dictionaries, but again - it seems to me
>that I'd need to dynamically create a dictionary whose name isn't known
>until runtime...
>
>Or am I missing the obvious? This is the most likely scenario :)
You should post some example code. I'm not sure I know what you're talking
about.
More information about the Python-list
mailing list