I need to add to the list a dictionary based on the number of elements in a given tuple. The idea is below:
# t is tuple containing 1 or 2 elements, l is list
l = list()
l.append({
'A': t[0],
if len(t) > 1: ('B': t[1])
})
So, if t = [7, 8] then l = [{'A': 7, 'B': 8}] and if t = [7] then l = [{'A': 7}].
How can I accomplish this?
-
The options are only one or two elements?Jblasco– Jblasco2014年11月29日 21:38:54 +00:00Commented Nov 29, 2014 at 21:38
-
Please reconsider which answer you have accepted. Jblasco's works, but ajcr's is much simpler.Colin vH– Colin vH2014年12月03日 16:19:14 +00:00Commented Dec 3, 2014 at 16:19
4 Answers 4
You could just use an if statement.
d = { 'A':t[0] }
if len(t) > 1:
d['B'] = t[1]
l = [d]
Or you could use a comprehension:
l = [ { chr(ord('A')+i):v for i,v in enumerate(t) } ]
That will work if the length of your tuple is between 0 and 26. (After that you run out of letters.)
Comments
Alternatively you could write the following line to create the dictionary:
[dict(zip(['A', 'B'], t))]
Then if t = [7, 8]:
>>> [dict(zip(['A', 'B'], t))]
[{'A': 7, 'B': 8}]
And if t = [7]:
>>> [dict(zip(['A', 'B'], t))]
[{'A': 7}]
The function zip creates tuples from t and the list of letters only up to the length of the shortest list. dict maps the tuples to dictionary keys/values.
Comments
Since the zip function stops in the shortest of the two emails, I like the option:
l.append({key:value for key, value in zip(['A', 'B'], t)})
3 Comments
{key: value for key, value in ...} is equivalent to dict(...).import string and use string.letters.upper()[:26] in the palce of ['A', 'B']. It makes it a little more extensible in case you don't know the length of t.Your conditional expression should be written like so:
l.append({'A': t[0], 'B': t[1]} if len(t) > 1 else {'A': t[0]})
If the tuple has more than one item, then we add {'A': t[0], 'B': t[1]} to the list. Otherwise, we add {'A': t[0]}.
Alternately, you could add dict(zip('AB', t)) to the list:
l.append(dict(zip('AB', t)))
this will work in either case:
>>> t = (1, 2)
>>> dict(zip('AB', t))
{'A': 1, 'B': 2}
>>> t = (1,)
>>> dict(zip('AB', t))
{'A': 1}
>>>