1

I have a list like the following:

some_list = [   
    'fullname',
    'John Kroes',
    'email',
    'johnkroes1978@example.com',
    'password',
    '3kKb5HYag'
]

How can I convert it to a dictionary like the one shown below?

some_dict = {
    'fullname': 'John Kroes',
    'email': 'johnkroes1978@example.com',
    'password': '3kKb5HYag'
}

I tried to do it using nested loops, but I do not know how to write down the key first, and then its value.

I also made a temporary variable before the loop, after which I wrote down the current loop element in it and tried to use it as a value in the try.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
kshnkvn
  • 876
  • 2
  • 18
  • 31

3 Answers3

5

There are lots of ways. One very simple way is to split the list:

keys = some_list [::2]
vals = some_list [1::2]
some_dict = dict(zip(keys, vals))

A more general approach might be to use iterators:

it = iter(some_list)
some_dict = dict(zip(it, it))

This approach is nicer for two reasons. First, you don't have to make temporary lists. Second, it works for any iterable, even if it isn't an indexable sequence.

The arguments to zip must be the same iterator object for this to work: each call to next steps the iterator forward, so getting a key for the output tuple positions the iterator to get the value immediately after.

Here is the one-liner equivalent:

some_dict = dict(zip(*[iter(some_list)] * 2))
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
1

You can take advantage of dict() constructor (doc), that accepts tuples of (key, value):

some_list = [
    'fullname',
    'John Kroes',
    'email',
    'johnkroes1978@example.com',
    'password',
    '3kKb5HYag'
]

print(dict((k, v) for k, v in zip(some_list[::2], some_list[1::2]))) # or shorter print(dict(zip(some_list[::2], some_list[1::2])))

Prints:

{'fullname': 'John Kroes', 'email': 'johnkroes1978@example.com', 'password': '3kKb5HYag'}
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

Use list slicing to pull out the keys (some_list[0::2]) and values (some_list[1::2]) as separate lists. Then use zip() to pair up elements from the two parallel lists.

>>> dict(zip(some_list[0::2], some_list[1::2]))
{'fullname': 'John Kroes', 'email': 'johnkroes1978@example.com', 'password': '3kKb5HYag'}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578