Reputation: 143
I want my list to be converted into Dictionary E.g
list1=["Indrajit","Mayur","Swapnali","Akankasha"]
into Dictionary having Automatically generated keys like
dict1 = {"1" : "indrajit","2" : "Mayur", "3" : "Swapnali", "4" : "Akankasha"}
Upvotes: 1
Views: 88
Reputation: 140178
You could use enumerate
starting at 1 and convert index as string, in a dictionary comprehension:
list1=["Indrajit","Mayur","Swapnali","Akankasha"]
dict1 = {str(k):v for k,v in enumerate(list1,1)}
print(dict1)
result:
{'1': 'Indrajit', '4': 'Akankasha', '2': 'Mayur', '3': 'Swapnali'}
Upvotes: 2
Reputation: 1
Try this
List<string> list = new List<string>() { "Indrajit", "Mayur", "Swapnali", "Akankasha" };
Dictionary<int, string> di = new Dictionary<int, string>();
for (int i = 1; i <= list.Count; i++)
{
di.Add(i, list[i - 1]);
}
Upvotes: 0
Reputation: 4964
Just use
dict1 = dict(enumerate(list1))
enumerate will return a generator that returns a tuple with index and list value, one at a time. By calling dict() you totally consume the generator, getting what you want.
Upvotes: 0
Reputation: 11477
You can use enumerate
method to do this:
>>> dict(enumerate(list1,1))
{1: 'Indrajit', 2: 'Mayur', 3: 'Swapnali', 4: 'Akankasha'}
Also you can use list.index()
method:
>>> list1=["Indrajit","Mayur","Swapnali","Akankasha"]
>>> print({list1.index(i)+1,i} for i in list1 )
>>> print({list1.index(i)+1:i for i in list1})
{1: 'Indrajit', 2: 'Mayur', 3: 'Swapnali', 4: 'Akankasha'}
But if there're duplicate items in your list, it maybe return unexpected result.
Upvotes: 1