Reputation: 4052
I am building a list in python by looping through some JSON blobs and appending elements. Sometimes the elements are single, sometimes double (or more).
my_list = []
for j in jsons:
my_list.append(j['foo'])
my_list
ends up being ['a1', 'b1', ['c1', 'c2']]
If I use extend instead I get ['a', '1', 'b', '1', 'c1', 'c2']
.
Do I have to first check if what I'm appending is a list, and then append it element-wise? Or is there a better function that already does this?
Upvotes: 0
Views: 169
Reputation: 531430
You can use the singledispatch
decorator to move some of the boilerplate out of your main loop. The decorator is available from the functools
module in the standard library starting in Python 3.4, or via the singledispatch
module on PyPi.
This defines a function adder
which behaves differently depending on the type of its (first) argument.
@singledispatch
def adder(item):
mylist.append(item)
@adder.register(list)
def _(item):
mylist.extend(item)
mylist = []
for json in jsons:
adder(json['foo'])
Upvotes: 2
Reputation: 22962
Yes, you need to explicitly check each item type.
For instance, you can write:
# sample jsons
jsons = [{'foo': 'a1'},
{'foo': 'b1'},
{'foo': ['c1', 'c2']}]
my_list = []
for json in jsons:
item = json['foo']
if isinstance(item, list):
my_list.extend(item)
else:
my_list.append(item)
You get:
['a1', 'b1', 'c1', 'c2']
But, with Python you can use a ternary conditional expression to simplify:
my_list = []
for json in jsons:
item = json['foo']
my_list.extend(item if isinstance(item, list) else [item])
Upvotes: 3