0

How to exclude the key 'u' from below,

{u'{"auth":{"user_id":"2"},"data":{"collection":"master-services"}}': [u'']}

I need to get my dictionary like below,

{"auth":{"user_id":"2"},"data":{"collection":"master-services"}}
Nuju
  • 322
  • 6
  • 17
  • 4
    I have a strong reason to believe that instead of converting it to your desired format, you should have initially written it in the desired format of nested dict objects (until and unless the data is getting served from some third party) – Moinuddin Quadri Jan 22 '18 at 06:18
  • Your 'list' is not a list, it is a dictionary. – DYZ Jan 22 '18 at 06:21
  • 1
    Possible duplicate of [Removing u in list](https://stackoverflow.com/questions/9773121/removing-u-in-list) – tripleee Jan 22 '18 at 06:32
  • And yet, the same broad answer applies. "Removing u in dict" is basically the same as "Removing u in list". – tripleee Jan 22 '18 at 06:33
  • This thread is probably relevant: https://stackoverflow.com/questions/13940272/python-json-loads-returns-items-prefixing-with-u – Avidan Efody Jan 09 '20 at 10:40

2 Answers2

4

It looks like you have a dictionary where the key(s) is JSON data. Try parsing it with a JSON parser.

>>> json.loads(list(data)[0])
{'auth': {'user_id': '2'}, 'data': {'collection': 'master-services'}}

If you have many such keys, you can iterate over data (or, data.keys()), like this:

>>> new_data = [json.loads(d) for d in data]

This gives you a list of dictionaries.

cs95
  • 379,657
  • 97
  • 704
  • 746
1

u stands for Unicode Text. It is used for creating Unicode strings. It is not a character that's stored in the dictionary.

You just need the key of the dictionary entry. Because there is only one key, you can do this:

my_dict = {u'{"auth":{"user_id":"2"},"data":{"collection":"master-services"}}': [u'']}
my_key = next(iter(my_dict))

my_key will hold the value {"auth":{"user_id":"2"},"data":{"collection":"master-services"}}

Hector Ricardo
  • 497
  • 5
  • 16