-5

Here is the output I want to convert from tuples to dict:

(198, [u'http://domain.com', u'http://domain2'])
(199, [u'http://domain3.com/', u'http://www.domain4'])

it should come out like:

(198: [u'http://domain.com', u'http://domain2']),
(199: [u'http://domain3.com/', u'http://www.domain4'])

I tried all kinds of things in for loop:

for item in opa.items():        
    aa = {(y:[x]) for y,[x] in item}

But always end up getting the same error:

TypeError: 'int' object is not iterable

Even better solution would be to create dict instead of tuples at "creation of output"(using now)

opa = defaultdict(list)
a3 = [model.objects.get(keyword=keyword).url]
for k in a3:
    opa[keyword].append(k)

I tried something like this, but it does't 'add' list of domains to key... it just added one:

opa = defaultdict(dict)
a3 = [model.objects.get(keyword=keyword).url] # returns list of urls
for k in a3:
    opa[keyword] = [k]
Nema Ga
  • 2,450
  • 4
  • 26
  • 49
  • Possible duplicate of [python tuple to dict](http://stackoverflow.com/questions/3783530/python-tuple-to-dict) – YOBA Oct 14 '15 at 13:11
  • Do you want a list of dicts like your broken syntax somewhat indicates? (e.g. `[{198: [...]}, {199: [...]}]`) or do you want a single dict? (e.g. `{198: [...], 199: [...]}`) – Adam Smith Oct 14 '15 at 13:35

2 Answers2

2

If you want to convert a list of tuples of the form (key, value) into a dictionary, you could use dictionary comprehension:

{x:y for (x, y) in tuples}
dorverbin
  • 467
  • 1
  • 4
  • 17
-1

This did the trick:

opa = dict(opa)

for item, k in opa.items():        
    aa = {item:k}
Nema Ga
  • 2,450
  • 4
  • 26
  • 49
  • 1
    While this answer may be correct, please add some explanation. Imparting the underlying logic is more important than just giving the code, because it helps the OP and other readers fix this and similar issues themselves. – CodeMouse92 Oct 14 '15 at 17:00