Reputation: 187
Input is given as a = "test1,test2,test3,test4,...etc"
I want the output like below:
b={"test1":"test1","test2":"test2","test3":"test3",..etc}
Please let me know how can I do this.
Upvotes: 1
Views: 106
Reputation: 1121724
To create a dictionary in a loop, use a dict comprehension.
Assuming that your a
variable is a string with comma-separated values, the following would work:
{v: v for v in a.split(',')}
where we use each value in the comma-separated list as both key and value for the resulting dictionary.
The {k: v ...}
dict comprehension was added in Python 2.7 and 3.0, in earlier python versions generate 2-value tuples instead:
dict((v, v) for v in a.split(','))
Upvotes: 6
Reputation: 9584
An addition to Martijn Pieters' correct answer:
The dict comprehension only works with Python versions >= 2.7. For earlier versions of Python, you can create 2-valued tuples and pass them to the dict()
function:
dict((item, item) for item in a.split(','))
And, finally, to mention this option as well, this would be the long way:
d = {} # alternatively, d = dict()
for item in a.split(','):
d[item] = item
Upvotes: 2