-2

My problem is similar to this.

Instead of populating the dictionary with a single number, I want to populate this with a string of numbers. I've got a long string of numbers separated at interval 7 by a comma.

I've got something like this,

values = '123456,789101,2345678' # (a string of numbers)

keys = [1,2,3] 

I want to create a dictionary like something below:

my_dict = {1: '123456', 2: '789101', 3: '2345678'}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Does key always start at `1` and is strictly increasing with `1`? – Ludisposed Jun 13 '17 at 06:59
  • 1
    `values` appears to be a tuple of integers, but you are saying it is a *string* of numbers? Can you please clarify? – Martijn Pieters Jun 13 '17 at 07:02
  • Given that you responded to one of the answers with 'Works perfectly fine', I've updated both your input and your expected output to match the assumptions that answerer made (input is a string with digits and commas, output dictionary values are strings too). – Martijn Pieters Jun 13 '17 at 07:13

3 Answers3

1

Try this:

>>> values = '123456,789101,2345678'
>>> 
>>> keys = [1,2,3]
>>> 
>>> 
>>> dict(zip(keys, values.split(',')))
{1: '123456', 2: '789101', 3: '2345678'}
>>> 
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
1

You could do something like this:

>>> values = '123456,789101,2345678'
>>> my_dict = {i+1:j for i,j in enumerate(values.split(','))}

Outputs

>>> print (my_dict) 
>>> {1: '123456', 2: '789101', 3: '2345678'}
Ludisposed
  • 1,709
  • 4
  • 18
  • 38
1
In [1]: values = '123456,789101,2345678'

In [2]: dict(enumerate(values.split(','), 1))
Out[2]: {1: '123456', 2: '789101', 3: '2345678'}
vishes_shell
  • 22,409
  • 6
  • 71
  • 81