Creating variables from dicts

Luis M. González luismgz at
Tue Feb 23 23:56:30 CET 2010

On Feb 23, 5:53 pm, vsoler < at> 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
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...

More information about the Python-list mailing list