简体   繁体   中英

Why does this Python list of dictionary only have the keys of the dictionary?

I wrote a module, which is serving as a config file:

users = list(
             dict(
                  username="x",
                  password="y"
                  )
             )

However, when I inspect the imported contents of the list, it contains the keys of the dictionary, not a dictionary entry:

>>> import user as userdata
import user as userdata
>>> userdata.users
userdata.users
['username', 'password']
>>> 

You are not making a list of dicts, you are making a list of dictionary keys from the dictionary, list(dict(...)) returns a list of keys:

>>> d = dict(username="x", password="y")
>>> list(d)
['username', 'password']

Probably you want to define users this way:

users = [dict(username="x", password="y")]

or

users = [{'username': 'x', 'password': 'y'}]

这是因为当你在字典上调用list时,它会生成一个只有你的键的新列表,这与使用yourdictionary.keys()的方法调用相同。

You are creating the list from a dictionary. The list constructor will iterate over the dict, which just gives the keys.

If you want a list that contains the dict as one element, you can use:

[dict(username='test')]

Try with:

 users = [dict(username="x",password="y")]
 print users

if you want to have array of dictionaries.

I can't understand why would you use dict( ) when you can simply use { } ..

You know the dictionary functions? If not I'd recommend you to try the dir() function.

There are some functions in there that you can use:

dictionary. keys() , returns a list of all the keys in the dictionary.

dictionary. values() , returns a list of all the values in the dictionary.

dictionary. items() , returns a list which in each cell there are 2 'variables', [0]=key, [1]=value

Example:

d = { "First":1, "Second":2 }
d.keys()
>> [ "First", "Second" ]
d.values()
>> [ 1, 2 ]
d.items()
>> [ ("First", 1), ("Second", 2) ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM