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

Converting dictionary value from string to float

P: 2
Hello:

I am new to Python (and a programming greenie for that matter) and I was trying to figure out how to change the "value" of my dictionary dataset from a string to a float. I imagine it is easy, but I haven't been able to figure it out.
Expand|Select|Wrap|Line Numbers
  1. data_list ={'11': '0.0', '10': '0.0', '13': '0.0', '12': '10.0', '15': '10.0', '14': '10.0', '17': '10.0', '16': '10.0', '19': '10.0', '18': '10.0', '20': '10.0', '1': '10.0', '3': '0.0', '2': '0.0', '5': '0.0', '4': '0.0', '7': '0.0', '6': '0.0', '9': '0.0', '8': '0.0', '21': '10.0'}
Any help would be appreciated!
Nov 16 '07 #1
Share this Question
Share on Google+
3 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Hello:

I am new to Python (and a programming greenie for that matter) and I was trying to figure out how to change the "value" of my dictionary dataset from a string to a float. I imagine it is easy, but I haven't been able to figure it out.

data_list ={'11': '0.0', '10': '0.0', '13': '0.0', '12': '10.0', '15': '10.0', '14': '10.0', '17': '10.0', '16': '10.0', '19': '10.0', '18': '10.0', '20': '10.0', '1': '10.0', '3': '0.0', '2': '0.0', '5': '0.0', '4': '0.0', '7': '0.0', '6': '0.0', '9': '0.0', '8': '0.0', '21': '10.0'}

Any help would be appreciated!
This should do it
Expand|Select|Wrap|Line Numbers
  1. newDict = dict(zip(data_list.keys(), [float(value) for value in data_list.values()]
Nov 16 '07 #2

P: 2
Worked great! Thanks.

P.S. I must be green for naming a dictionary "data_list".....
Nov 16 '07 #3

bartonc
Expert 5K+
P: 6,596
Hello:

I am new to Python (and a programming greenie for that matter) and I was trying to figure out how to change the "value" of my dictionary dataset from a string to a float. I imagine it is easy, but I haven't been able to figure it out.
Expand|Select|Wrap|Line Numbers
  1. data_list ={'11': '0.0', '10': '0.0', '13': '0.0', '12': '10.0', '15': '10.0', '14': '10.0', '17': '10.0', '16': '10.0', '19': '10.0', '18': '10.0', '20': '10.0', '1': '10.0', '3': '0.0', '2': '0.0', '5': '0.0', '4': '0.0', '7': '0.0', '6': '0.0', '9': '0.0', '8': '0.0', '21': '10.0'}
Any help would be appreciated!
My friend bvdet has a great solution, but all those () and [] can be a bit daunting for a beginner. To make it look simpler, let's break it in its basic parts:
Expand|Select|Wrap|Line Numbers
  1. newDict = {} # an empty dictionary
  2. for key, value in data_list.items(): # get the (key, value) tuples one at a time
  3.     newDict[key] = value
Nov 16 '07 #4

Post your reply

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