-1

I have a user defined list(so it is not static.For example's sake let's say the user entered the following elements in the list)

['sam', '25', 'matt', '30', 'jack', '27']

Is it possible to convert it into dictionary with name as key and age as value?

klaptor
  • 115
  • 10
  • So you want something like `[{'name': 'sam', 'age': 25}, {'name': 'matt', 'age': 30}, ...]`? – fedorqui Aug 31 '18 at 09:49
  • 1
    If it's always in pairs, then `dict(zip(data[::2], data[1::2]))` ? – Jon Clements Aug 31 '18 at 09:50
  • @fedorqui yes.I want something like that – klaptor Aug 31 '18 at 09:53
  • @klaptor then you should show your attempts, please [edit] to explain properly your required output (for example witht the format I provided) and what you tried :) – fedorqui Aug 31 '18 at 09:56
  • 1
    @klaptor then the solution is in Jon Clements comment - but you actually have a design issue in the way the data are collected, they should already be grouped together (as a dict or as a list of `(name, age)` tuples) instead of being dumped that way in a list. A list is supposed to be homogenous - items in the list should not have a different meaning depending on their position in the list. IOW, you'd better fix the issue at the source. – bruno desthuilliers Aug 31 '18 at 09:59
  • @brunodesthuilliers I'm new to python but I understand now where I made mistake.Thanks for the explaintaion! – klaptor Aug 31 '18 at 10:03
  • 1
    @klaptor note that this issue is nothing python-specific, it'a about proper data structure design whatever the language. – bruno desthuilliers Aug 31 '18 at 10:05

3 Answers3

2

You may use zip to create tuples of key-value pairs and then type-cast these to dict as:

>>> my_list = ['sam', '25', 'matt', '30', 'jack', '27']

>>> dict(zip(my_list[::2], my_list[1::2]))
{'matt': '30', 'jack': '27', 'sam': '25'}

Or you may use a dictionary comprehension with range as:

>>> {my_list[i]: my_list[i+1] for i in range(0, len(my_list), 2)}
{'matt': '30', 'jack': '27', 'sam': '25'}

Performance comparison of both the solutions:

# Using `zip`
mquadri$ python -m timeit -s "my_list = ['sam', '25', 'matt', '30', 'jack', '27']" "{my_list[i]: my_list[i+1] for i in range(0, len(my_list), 2)}"
1000000 loops, best of 3: 0.872 usec per loop

# Using "dictionary comprehension"
mquadri$ python -m timeit -s "my_list = ['sam', '25', 'matt', '30', 'jack', '27']" "dict(zip(my_list[::2], my_list[1::2]))"
1000000 loops, best of 3: 1.53 usec per loop
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

Dict constructor accepts an iterable of (key, value) tuples. So, you just have to iterate over the list two at a time

def two_at_time(iterable):
    args = [iter(iterable)] * 2
    return zip(*args)

lst = ['a', 5, 'b', 6]

my_dict = dict(two_at_time(lst))
blue_note
  • 27,712
  • 9
  • 72
  • 90
0

result_dict={}

for i in range(0,len(a),2):
       result_dict[a[i]]=a[i+1]

output :

 {'sam': '25', 'matt': '30', 'jack': '27'}
mukesh kudi
  • 719
  • 6
  • 20