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

how to convert a sting to dictionary without knowing the string??

P: 1
i m new to python i have converted a list to dictionary ,as i know my sentence so easily i can convert ,,bt i want to knw how to convert tht list to dictionary when we didint kow the string..
Apr 18 '19 #1
Share this Question
Share on Google+
2 Replies

P: 1
1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

from ast import literal_eval

python_dict = literal_eval("{'a': 1}")
2. json.loads but it would require your string to use double quotes:

import json

python_dict = json.loads('{"a": 1}')
Apr 18 '19 #2

Expert 100+
P: 1,035
First of all you keyboard needs to be renewed, some characters are missing.... 😉😉

I am new to python too, maybe this code can help a bit?:
Expand|Select|Wrap|Line Numbers
  1. a='Type "help", "copyright", "credits" or "license" for more information.'
  2. c=1
  3. d={}
  4. for b in a.split():
  5.   print(b)
  6.   d[c]=b
  7.   c=c+1
After this 'd' contains a dictionary.

For example 'd[2]' will contain the second word in the sentence.
Apr 20 '19 #3

Post your reply

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