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

Converting dictionary values from list of strings to list of list.

P: 1
I dispose of a dictionary whose values look like a list of strings (d_pro):
Expand|Select|Wrap|Line Numbers
  1. d_pro={'1': ['1,2,3', '4,5,6'], '2': ['1,2,3', '4,5,6']}
I'd like to turn it into a dictionary whose values look like a list of lists (expected output in d_pro_list) for further processing:
Expand|Select|Wrap|Line Numbers
  1. d_pro_list= {'1': [['1,2,3'], ['4,5,6']], '2': [['1,2,3'], ['4,5,6']]}
I'm trying the given code:
Expand|Select|Wrap|Line Numbers
  1. d_pro_list={}
  2. for k in d_pro.keys():
  3.     for v in d_pro.values():
  4.         for i in v:
  5.             d_pro_list[k]= [i]
But the output is like:
Expand|Select|Wrap|Line Numbers
  1. d_pro_list= {'1': ['1,2,3,4,5,6'], '2': ['1,2,3,4,5,6']}
Can you please help me finding my mistakes? Thanks.
Jul 16 '14 #1
Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
I am unsure how you actually want it, so I will show both:
Expand|Select|Wrap|Line Numbers
  1. >>> 
  2. >>> d_pro={'1': ['1,2,3', '4,5,6'], '2': ['1,2,3', '4,5,6']}
  3. >>> for key in d_pro:
  4. ...     d_pro[key] = [item.split(",") for item in d_pro[key]]
  5. ...     
  6. >>> d_pro
  7. {'1': [['1', '2', '3'], ['4', '5', '6']], '2': [['1', '2', '3'], ['4', '5', '6']]}
  8. >>> d_pro={'1': ['1,2,3', '4,5,6'], '2': ['1,2,3', '4,5,6']}
  9. >>> for key in d_pro:
  10. ...     d_pro[key] = [[item] for item in d_pro[key]]
  11. ...     
  12. >>> d_pro
  13. {'1': [['1,2,3'], ['4,5,6']], '2': [['1,2,3'], ['4,5,6']]}
  14. >>> 
Jul 16 '14 #2

Post your reply

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