How can i get from list a numbered dictionary?

This is the place for queries that don't fit in any of the other categories.

How can i get from list a numbered dictionary?

Postby Mike Ru » Sat Sep 24, 2016 1:09 pm

I have the list:
Code: Select all
s = ['Programmer', 'Driver', 'Cooker', 'Fighter']

I need it:
Code: Select all
d = [1: 'Programmer', 2: 'Driver', 3: 'Cooker', 4: 'Fighter']

I do it so:
Code: Select all
s = ['Programmer', 'Driver', 'Cooker', 'Fighter']
count = len(s) + 1
int_s = list(range(count))[1:]
d = dict(zip(int_s, s))
print(d)


How can I do it simpler than i wrote above?
Last edited by Yoriz on Sat Sep 24, 2016 1:16 pm, edited 1 time in total.
Reason: Added code tags to input and expetced output.
Mike Ru
 
Posts: 8
Joined: Sat Apr 23, 2016 6:13 pm

Re: How can i get from list a numbered dictionary?

Postby Yoriz » Sat Sep 24, 2016 1:15 pm

Code: Select all
s = ['Programmer', 'Driver', 'Cooker', 'Fighter']

d = {index:value for index, value in enumerate(s, 1)}
print(d)

or
Code: Select all
s = ['Programmer', 'Driver', 'Cooker', 'Fighter']

d= dict(enumerate(s, 1))
print(d)

Output
Code: Select all
{1: 'Programmer', 2: 'Driver', 3: 'Cooker', 4: 'Fighter'}
Due to the reasons discussed here we will be moving to python-forum.io/ on October 1 2016
This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.
User avatar
Yoriz
 
Posts: 1672
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: How can i get from list a numbered dictionary?

Postby Mike Ru » Sat Sep 24, 2016 1:23 pm

Yoriz wrote:
Code: Select all
s = ['Programmer', 'Driver', 'Cooker', 'Fighter']

d = {index:value for index, value in enumerate(s, 1)}
print(d)

or
Code: Select all
s = ['Programmer', 'Driver', 'Cooker', 'Fighter']

d= dict(enumerate(s, 1))
print(d)

Output
Code: Select all
{1: 'Programmer', 2: 'Driver', 3: 'Cooker', 4: 'Fighter'}


Thank you very much.
Mike Ru
 
Posts: 8
Joined: Sat Apr 23, 2016 6:13 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 7 guests