-1

I have a tuple like this

([(a,),(b,),...],[(x,),(y,),...])

I want to transform it into a dictionary like this:

sozluk={"a":x,"b":y,...}

I am looking for a practice way to realize that

  • There are something you need to declare:Do them have the same length?What have you tried?(`tuple[0]` and `tuple[1]`) – jizhihaoSAMA Jun 03 '20 at 15:39
  • Are both the list equal in length? – arshovon Jun 03 '20 at 15:39
  • 1
    seems like a straightforward dictionary comprehension using `zip` should work. Also -- are `a`, `b`, `c`, etc. already strings? If not, what are they? Something like `{s[0]:t[0] for s,t in zip(*tuples)}` – John Coleman Jun 03 '20 at 15:40
  • both are in the same length. the left side list is timestamp values as DateTime, right side list is actual values as the float. – automatickebab Jun 03 '20 at 15:46

3 Answers3

2
t = ([(1,),(2,),(3,)],[('a',),('b',),('c',)])

r = {key[0]: value[0] for key, value, in zip(t[0],t[1])}

Demetry Pascal
  • 383
  • 4
  • 15
1

This works also in Python2.7 and Python3 (I use ' to create string instead of variable, just for test):

    q = ([('a',),('b',)],[('x',),('y',)])
    print({k[0]:v[0] for k,v in zip(*q)})

    {'a': 'x', 'b': 'y'}
0

Usually, a simple zip should work, but in your case, each item is a tuple instead of a single element. So here, I use a simple list comprehension to convert the tuple into keys and values, and then create the dictionary based on those with a simple zip (more on this):

>>> t = ([("a",),("b",)], [("x",),("y",)])
>>> keys = [i[0] for i in t[0]]
>>> keys
['a', 'b']
>>> values = [i[0] for i in t[1]]
>>> values
['x', 'y']
>>> dict(zip(keys, values))
{'a': 'x', 'b': 'y'}
nima72
  • 36
  • 2