468,268 Members | 1,977 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,268 developers. It's quick & easy.

How to create a list of dictionaries?

Hi,

I am quite new to Python & recently I have been given an assignment to create a list of dictionaries.
Can anyone give me an idea of how to do so?

Let say, my dictionary will have 3 keys: "FirstName", "LastName" , and "SSID".

So the expected output would be:
dictList = [ {'FirstName': 'Michael', 'LastName': 'Kirk', 'SSID': '224567'},
{'FirstName': 'Linda', 'LastName': 'Matthew', 'SSID': '123456'},
{'FirstName': 'Sandra', 'LastName': 'Parkin', 'SSID': '123456'},
{'FirstName': 'Bob', 'LastName': 'Henry', 'SSID': '666666'},
{'FirstName': 'Silvia', 'LastName': 'Perkin', 'SSID': '676767'}]

And assuming after having the above list, how can I retrieve the info of each dictionary entry?

Thanks in advance

Leny
Mar 11 '08 #1
4 137991
jlm699
314 100+
One way is to simply use the append() function of a list.

Expand|Select|Wrap|Line Numbers
  1. >>> lst = []
  2. >>> lst.append({'fn':'b','ln':'d'})
  3. >>> lst.append({'fn':'a', 'ln':'c'})
  4. >>> print lst
  5. [{'fn':'b', 'ln':'d'}, {'fn':'a', 'ln':'c'}]
  6. >>> for elem in lst:
  7.             print elem['fn'], elem['ln']
  8. b d
  9. a c
  10.  
Mar 11 '08 #2
bvdet
2,851 Expert Mod 2GB
Also using the list append method similar to jlm699's post, you can do something like this:
Expand|Select|Wrap|Line Numbers
  1. keys = ['FirstName', 'LastName', 'SSID']
  2.  
  3. name1 = ['Michael', 'Kirk', '224567']
  4. name2 = ['Linda', 'Matthew', '123456']
  5.  
  6. dictList = []
  7. dictList.append(dict(zip(keys, name1)))
  8. dictList.append(dict(zip(keys, name2)))
  9.  
  10. print dictList
  11. for item in dictList:
  12.     print ' '.join([item[key] for key in keys])
Printed output:

>>> [{'LastName': 'Kirk', 'SSID': '224567', 'FirstName': 'Michael'}, {'LastName': 'Matthew', 'SSID': '123456', 'FirstName': 'Linda'}]
Michael Kirk 224567
Linda Matthew 123456
>>>
Mar 11 '08 #3
jlm699
314 100+
Expand|Select|Wrap|Line Numbers
  1. dictList.append(dict(zip(keys, name1)))
  2.  
That is awesome... I never knew about zip() ... that is going to help my dictionary implementations immensely!
Mar 11 '08 #4
Cool! Thank you so much for the replies!

I ll try it out, shall post again if I have any further doubt.

Shige
Mar 11 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

reply views Thread by Helge V. Larsen | last post: by
5 posts views Thread by ericdaniel | last post: by
4 posts views Thread by shapper | last post: by
reply views Thread by NPC403 | last post: by
reply views Thread by zattat | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.