Learning about dictionaries

wes weston wweston at att.net
Fri Apr 16 15:41:02 EDT 2004


Thomas Philips wrote:
> I'm teaching myself python and in the course of playing around with
> dictionaries, I tried to create the following trivial dictionary
> 
> {1:'one', 2:'two'}
> 
> So I entered
> 
>>>>dict(1='one',2='two')
> 
> SyntaxError: keyword can't be an expression
> 
> As this did not work, I tried
> 
>>>>dict(1=one,2=two)
> 
> SyntaxError: keyword can't be an expression
> 
> and
> 
>>>>dict('1'='one','2'='two')
> 
> SyntaxError: keyword can't be an expression
> 
> as well as
> 
>>>>dict('1'=one,'2'=two)
> 
> SyntaxError: keyword can't be an expression
> 
> Out of curiosity, I tried
> 
>>>>dict(one=1,two=2)
> 
> {'two': 2, 'one': 1}
> 
> Why does this last attempt work, and more importantly, why did my four
> earlier attempts fail? I might add that I have no trouble getting what
> I want with
> 
>>>>dict(zip((1,2),('one','two')))
> 
> {1: 'one', 2: 'two'}
> or
> 
>>>>dict(((1,'one'),(2,'two')))
> 
> {1: 'one', 2: 'two'}
> 
> Sincerely
> 
> Thomas Philips


Thomas,
    Does this help:

 >>> print(dict.__doc__)
dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object's
     (key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
     d = {}
     for k, v in seq:
         d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
     in the keyword argument list.  For example:  dict(one=1, two=2)
 >>>

wes




More information about the Python-list mailing list