Creating variables from dicts

Luis M. González luismgz at gmail.com
Wed Feb 24 00:41:16 CET 2010


On Feb 23, 7:56 pm, Luis M. González <luis... at gmail.com> wrote:
> On Feb 23, 5:53 pm, vsoler <vicente.so... at gmail.com> wrote:
>
>
>
>
>
> > Hi,
>
> > I have two dicts
>
> > n={'a', 'm', 'p'}
> > v={1,3,7}
>
> > and I'd like to have
>
> > a=1
> > m=3
> > p=7
>
> > that is, creating some variables.
>
> > How can I do this?
>
> You are probably coming from another language and you're not used to
> python's data structures.
> If you want a list of items, you use tuples or lists. Examples:
>
>     ('a', 'm', 'p') ---> this is a tuple, and it's made with
> parenthesis ()
>     ['a', 'm', 'p'] ---> this is a list, and it's made with brackets
> []
>
> Check the documentation to see the difference between tuples and
> lists.
> For now, lets just use lists and forget about tuples...
> Now if you want a sequence of items ordered a key + value pairs, use a
> dictionary, as follows:
>
>     {'name': 'joe', 'surname': 'doe', 'age': 21} ---> this is a dict,
> and it's made with curly braces {}.
>
> Curly braces are also used to create sets, but you don't need them now
> (check the documentation to learn more about sets).
> So going back to your question, you should have two lists, as follows:
>
>     n = ['a', 'm', 'p']
>     v = [1,3,7]         --> note that I used brackets [], not curly
> braces {}.
>
> And now you can build a dict formed by the keys in "n" and the values
> in "v":
>
>     myDict = {}           --> this is an new empty dictionary
>     for k,v in zip(n,v):
>         myDict[k] = v
>
> This results in this dictionary: {'a': 1, 'p': 7, 'm': 3}.
>
> Hope this helps...
> Luis

By the way, if you want the variables inside myDict to be free
variables, you have to add them to the local namespace.
The local namespace is also a dictionary "locals()".
So you can update locals as follows:

    locals().update( myDictionary )

This way, all the key-value pairs inside myDict become free variables.
Wich is the same as declaring them as follows:

    a = 1
    p = 7

etc...

Luis






More information about the Python-list mailing list