By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,235 Members | 1,022 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,235 IT Pros & Developers. It's quick & easy.

How to create a list of dictionaries?

P: 8
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
Share this Question
Share on Google+
4 Replies


jlm699
100+
P: 314
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
Expert Mod 2.5K+
P: 2,851
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
100+
P: 314
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

P: 8
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.