Why is there only dictionary keys in this list of Python dictionaries?

I wrote a module that serves as a configuration file:

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

However, when I check the imported contents of the list, it contains the keys of the dictionary, not the dictionary:

 >>> import user as userdata import user as userdata >>> userdata.users userdata.users ['username', 'password'] >>> 
+4
source share
5 answers

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

If you need a list containing a dict as a single element, you can use:

 [dict(username='test')] 
+1
source

You do not make a list of dicts, you make a list of dictionary keys from a dictionary, list(dict(...)) returns a list of keys:

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

Perhaps you want to define users as follows:

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

or

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

Because when you call list in the dictionary, it creates a new list of only your keys, which is similar to calling yourdictionary.keys() method.

+1
source

Try:

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

if you want to have an array of dictionaries.

0
source

I don’t understand why you use dict( ) when you can just use { } ..

Do you know the functions of the dictionary? If not, I recommend you try the dir() function.

There are some functions you can use:

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

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

. items() returns a list that in each cell contains 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) ] 
0
source

Source: https://habr.com/ru/post/1499407/


All Articles