How to create an array which can be used also as a dictionary

Diez B. Roggisch deets at nospam.web.de
Thu Sep 10 17:30:48 CEST 2009


Hans Müller wrote:

> Hello,
> 
> I have a lot of items having a name and a given sequence.
> 
> To access these items fast in a sequence order they should be used as
> a list, but to be fetched fast by name they also should be in a
> dictionary.
> 
> Code could be something like this.
> 
> class item
> def __init__(name, value1, value2, value3):
> self.name = name
> self.value1 = value1
> self.value2 = value2
> 
> a = []
> a.append(item("foo", "bar", "text1"))
> a.append(item("xyz", "basd", "tsddsfxt1"))
> a.append(item("aax", "hello", "dont care"))
> 
> in a, i have my objects in given order, fast accessible by index, e.g.
> a[2] to get the third one. Fine.
> 
> Now I'd like to have a dict with references to thes objects like this:
> 
> d = {}
> for x in a:
> d[a.name] = a # do I get a copy of a here or a new reference ?!

Only a reference.

> 
> In d i now have a dict, fast accessible by name.
> But what happens if i modify
> a[1].value1 = 1000
> is
> d["aax"].value1 now 1000 or still "hello" as in this example ?

It's changed. Didn't you try that? 

Diez



More information about the Python-list mailing list