I would like to show you what is the problem, how you can solve it and how we can improve the solution.
Your code works if you put the line where you initialize the total variable before you use it.
In your version you are using it before it is instantiated and that is why you get the UnboundLocalError: local variable 'total' referenced before assignment error.
Here's the fix, once done it is easy to manipulate the result dictionary in order to add to it the "count" field containing the length:
data = [{"id":1,"name":"a"},{"id":2,"name":"b"},{"id":3,"name":"c"}]
def id_extract(data):
total = [] # I put the total variable initialization before its usage
myDict = {}
myDict.update( {'values': total} )
cur_count = {"count": len(data)}
for i in data:
j = {"id": i["id"]}
total.append(j) # As explained total must be initialized BEFORE we use it here
result = {}
result['count'] = len(data)
result['values'] = myDict['values']
return result
print(id_extract(data))
The code works as expected.
Can we improve it, what looks off?
Why two dictionaries, for example?
I would suggest to optimize it simply putting data into your result dictionary directly:
data = [{"id":1,"name":"a"},{"id":2,"name":"b"},{"id":3,"name":"c"}]
def id_extract(data):
result = {'count': len(data), 'values' : []}
for i in data:
result['values'].append({"id": i["id"]})
return result
print(id_extract(data))
Already better, right?
We can improve it even more using the power of Python's List Comprehensions:
List comprehensions provide a concise way to create lists. Common
applications are to make new lists where each element is the result of
some operations applied to each member of another sequence or
iterable, or to create a subsequence of those elements that satisfy a
certain condition.
data = [{"id":1,"name":"a"},{"id":2,"name":"b"},{"id":3,"name":"c"}]
def id_extract(data):
result = {'count': len(data)}
result['values'] = [{"id": item["id"]} for item in data]
return result
print(id_extract(data))
At this point we keep on optimizing following the same techniques we used so far and we get the function in its final (well, for me :) ) form:
data = [{"id":1,"name":"a"},{"id":2,"name":"b"},{"id":3,"name":"c"}]
def id_extract(data):
return {'count': len(data), 'values' : [{"id": item["id"]} for item in data]}
print(id_extract(data))
Output
{'count': 3, 'values': [{'id': 1}, {'id': 2}, {'id': 3}]}