Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dictionary to tuple with additional element inside tuple

Let's say I have this dictionary:

d = {'a': 1, 'b': 2, 'c': 3}

So doing d.items(), it would convert it to:

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

But I need it to be like this:

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

What would be most pythonic/efficient way of doing it? Are there better alternatives than just iterating over a dictionary and building tuples for every key/value pair?

like image 254
Andrius Avatar asked Jun 22 '26 02:06

Andrius


1 Answers

You have to iterate over the dictionary and construct each tuple. Using a list comprehension, this is fairly straightforward to do:

>>> [(k, '=', v) for k, v in d.items()]
[('a', '=', 1), ('c', '=', 3), ('b', '=', 2)]
like image 113
Alex Riley Avatar answered Jun 23 '26 16:06

Alex Riley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!