How to recursively find specific key in nested JSON?

The JSON might contain a list of objects, which needs to be searched: Python 2.7 version: def item_generator(json_input, lookup_key): if isinstance(json_input, dict): for k, v in json_input.iteritems(): if k == lookup_key: yield v else: for child_val in item_generator(v, lookup_key): yield child_val elif isinstance(json_input, list): for item in json_input: for item_val in item_generator(item, lookup_key): yield item_val … Read more

How can I compare a unicode type to a string in python?

You must be looping over the wrong data set; just loop directly over the JSON-loaded dictionary, there is no need to call .keys() first: data = json.loads(response) myList = [item for item in data if item == “number1″] You may want to use u”number1” to avoid implicit conversions between Unicode and byte strings: data = … Read more

Sorting A List Comprehension In One Statement

The method list.sort() is sorting the list in place, and as all mutating methods it returns None. Use the built-in function sorted() to return a new sorted list. result = sorted((trans for trans in my_list if trans.type in types), key=lambda x: x.code) Instead of lambda x: x.code, you could also use the slightly faster operator.attrgetter(“code”).

What is the advantage of a list comprehension over a for loop?

List comprehensions are more compact and faster than an explicit for loop building a list: def slower(): result = [] for elem in some_iterable: result.append(elem) return result def faster(): return [elem for elem in some_iterable] This is because calling .append() on a list causes the list object to grow (in chunks) to make space for … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)