-1

I have a class Test with class parameter

parameters = {'first': [1,2,3,4], 'second': [5,6,7]}. I want to convert it into a dictionary so that it will be "{'Test': 'first':1 'second':5}"

what I tried is: di = {} di = dict(itertools.izip(name, vals))

where I'm getting Test i.e classnane in variable name i.e name = Test and

vals = {'first': [1,2,3,4], 'second': [5,6,7]} Though I want it as "{'Test': 'first':1 'second':5}", shouldn't this print "{'Test': 'first':[1,2,3,4] 'second':[5,6,7]}"?? Instead what I'm getting when I'm printing di is {'Test': 'first'}. I'm not getting where my logic is going wrong.

NikAsawadekar
  • 57
  • 1
  • 5

4 Answers4

4

Use a dictionary comprehension:

subjects = ['Physics', 'Chemistry', 'Maths']
{subject: {} for subject in subjects}
mgilson
  • 300,191
  • 65
  • 633
  • 696
2

If you are working with Python 2, you can use dict() constructor:

subjects =  ['Physics', 'Chemistry', 'Maths']
dict(((subject, {}) for subject  in subjects))

If you are using Python 3, you can use dictionary comprehension:

subjects =  ['Physics', 'Chemistry', 'Maths']
{subject: {} for subject in subjects}
jh314
  • 27,144
  • 16
  • 62
  • 82
1

Try using dict comprehension:

Input:

{x: {} for x in ['Physics', 'Chemistry', 'Maths']}

Output:

{'Maths': {}, 'Chemistry': {}, 'Physics': {}}
  • It looks like OP wants the items to be empty dicts -- If OP really wants an empty string, then `dict.fromkeys` is a great option. c.f. http://stackoverflow.com/q/14507591/748858 – mgilson Aug 18 '14 at 21:49
  • right, i realized that fact. dict comprehension is the solution to the question @mgilson –  Aug 18 '14 at 21:51
0

That is a basic for loop. Itertools is way to complex for this kind of stuff.

>>> l = ['Physics', 'Chemistry', 'Maths']
>>> d = {}
>>> for i in l:
    d[i] ={}


>>> d
{'Chemistry': {}, 'Physics': {}, 'Maths': {}}
  • Hey I tried it and got working but I have one question why it's in different order? Instead of {'Physics': {}, 'Chemistry': {}, 'Maths': {}} why we have - {'Chemistry': {}, 'Physics': {}, 'Maths': {}} ?? What I need to do to get it in right order? – NikAsawadekar Aug 19 '14 at 14:36
  • In python a dict is not sorted. If you really need to go through the dict sorted, just use `for key in sorted(d):`. P.S. this is just a simple for loop, the other answers are more efficient, faster and generally better. –  Aug 19 '14 at 14:45