0

Lately I got stuck trying to find an elegant solution to the following problem:

I have a Series object (pandas.core.series.Series) with the following values (e.g.) -

{1,43234,2,653543,3,436546}

I have another datasource on which I want to iterate, and for that I would like to create a dictionary out of the series, with the following format -

{1:43234,2:653543,3:436546}

Using the function .to_dict is not suitable as it auto-generates the keys.

Can anyone offer an idea?

Thank you all in advance!

2
  • 2
    {k:v for k, v in zip(s[::2], s[1::2])} ...? Commented Nov 20, 2019 at 13:15
  • so you want odd indexes to be your keys and even indexes to be your values? Commented Nov 20, 2019 at 13:15

1 Answer 1

2

For any indexable iterable – I'm pretty sure pd.Series applies – you can convert a [key, value, key, value, key, value] sort of thing to a dict by zipping slices with a stride:

>>> a = [1,43234,2,653543,3,436546]
>>> dict(zip(a[::2], a[1::2]))
{1: 43234, 2: 653543, 3: 436546}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.