James Pinson
James Pinson

Reputation: 221

Converting a string into a dictionary

I want to convert a string such as:

"this is a sentence"

and turn it into a dictionary such as:

{1:"this", 2:"is", 3:"a", 4:"sentence"}

any help would be appreciated

Upvotes: 1

Views: 79

Answers (2)

HennyH
HennyH

Reputation: 7944

>>> dict(enumerate("this is a sentence".split(),start=1))
{1: 'this', 2: 'is', 3: 'a', 4: 'sentence'}

Explination:

dict() accepts a iterable which contains tuples of the form (key,value). These are turned into key value pairs. split() will separate the sentence by whitespace. enumerate goes over all the values generated by .split and returns (index,value). These tuples are consumed by dict() producing the desired dictionary.

Upvotes: 4

Blender
Blender

Reputation: 298532

enumerate makes this simple:

dict(enumerate(sentence.split(), start=1))
  • sentence.split() splits up the sentence on whitespace into a list of words.
  • enumerate() makes an iterable of key-value pairs: [(1, 'this'), (2, 'is'), ...]
  • dict() accepts an iterable of key-value pairs and turns it into a dictionary.

Although if your keys are integers, why don't you just use a list?

Upvotes: 2

Related Questions