0

I have text a 1 b 2 c 3.

How can I make a dictionary in which letters would be keys, and numbers values?

I know how I would make it if it was in in multiple rows, I do not know how to do it when it is in one row.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

2 Answers2

3

Convert the string to list. And then list to dictionary.

str1 = "a 1 b 2 c 3"
lst = str1.split(" ")
dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Maleehak
  • 671
  • 8
  • 17
-1
text = "a 1 b 2 c 3"
myDictionary = {}
for i in range(0,len(text),4):
    myDictionary[text[i]]=text[i+2]
print(myDictionary)
#output : {'c': '3', 'a': '1', 'b': '2'} 
omkar
  • 71
  • 1
  • 6
  • This code will not work with the string given in the question. – mkrieger1 Jan 09 '21 at 12:02
  • if you have spaces you can use this, if you have two digit value then you should check for that , if you do not specify actually what you need then it become difficult to answer. – omkar Jan 09 '21 at 12:07
  • Now it works with the exact string given in the question, but what if there are numbers greater than 9 involved, for example `text = "a 10 b 12 c 32"`? – mkrieger1 Jan 09 '21 at 12:07
  • just split the string and convert into a list so it will be easier for you to make dictionary myList = list(text.split()) – omkar Jan 09 '21 at 12:09
  • so list will become [a,12,b,45,...] like that so using indexing you can make dictionary – omkar Jan 09 '21 at 12:10