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"}}
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.
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"}}
Related
I have a list of dictionaries, which looks like this:
car_list = [
{'Toyota': '{name}/Toyota'},
{'Mazda': '{name}/Mazda'},
{'Nissan': '{name}/Nissan'}
]
Now, using a regex, I want to replace all {name}s with another string (say "car"), and update the list of dictionaries. This is the code:
regex = r'\{.+?\}'
for dic in car_list:
for key, value in dic.items():
for name in re.findall(regex, value):
value = value.replace(name, "car")
dic.update(key=value)
I know as a fact that the regex part is working. However, I get this error:
RuntimeError: dictionary changed size during iteration
What am I doing wrong?
.update(key=value) inserts a new key into the dictionary where the key is the string literal 'key' and value value (as assigned in the line above).
You should use brackets to index into the dictionary, rather than calling .update():
for dic in car_list:
for key, value in dic.items():
for name in re.findall(regex, value):
value = value.replace(name, "car")
dic[key]=value
# Prints [{'Toyota': 'car/Toyota'}, {'Mazda': 'car/Mazda'}, {'Nissan': 'car/Nissan'}]
print(car_list)
There's no need to use a regex - str has two built-in methods, format and format_map, to replace fields marked with curly brackets, like your sample code:
msg = "Hello, {location}!"
print(msg.format(location="World"))
msg2 = "{greeting}, {place}!"
params = {"greeting": "Bonjour", "place": "Birmingham"}
print(msg2.format_map(params))
Using this:
for dct in car_list:
for key, value in dct.items():
dct[key] = value.format(name="car")
I have a list of dictionaries as a key value pairs, where I want to access the data of each dict by key:
sample data:
['"imageUrl":"/images/4.jpg"', '"number":"04047122"', '"name":"test"',...
real data
>>> data
['"imageUrl":"/images/products/klein/04047122_k.jpg"', '"art":"04047122"', '"productId":"170336"'; } } }) ']
This unfortunatelly does not work:
re.findall(r'(?:number\(\{)(.*)', data)[0].split(',')
How can I retrieve the values by name e.g. data['number'] ?
For a more robust solution, since each string in the input list is a valid line of CSV, delimited by a colon, you can use csv.reader to parse the list and then pass the resulting sequence of key-value pairs to the dict constructor to build a dict:
import csv
lst = ['"imageUrl":"/images/4.jpg"', '"number":"04047122"', '"name":"test"']
data = dict(csv.reader(lst, delimiter=':'))
You can then access data['number'] as desired.
Try to convert your data to a real dictionary:
data = ['"imageUrl":"/images/4.jpg"', '"number":"04047122"', '"name":"test"']
data_dict = dict([x.replace('"','').split(":") for x in data])
and then you will be able to access your keys:
print(data_dict["number"]) # output: 04047122
You can convert your string list to an actual dictionary easily:
>>> ls = ['"imageUrl":"/images/4.jpg"', '"number":"04047122"', '"name":"test"']
>>> data = dict(elem.replace('"', '').split(':') for elem in ls)
>>> data
{'imageUrl': '/images/4.jpg', 'number': '04047122', 'name': 'test'}
>>> data['number']
'04047122'
I have a list of dictionaries that is structured as such:
json_data = [{'a':10,'text':"Salam"},{'a':4,'text':"Hello Friend"}]
I have been able to iterate through the list and extract the key 'text' from each dictionary:
json1_text = [[[value] for value in json1_data[index].get('text')] for
index in range(len(json1_data))]
However, the new json1_text list does not contain sentences from returned from the dictionary, but rather each individual letter:
json1_text[0]
Returns:
[['S'],['a'],['l'],['a'],['m']]
How would I be able to return the whole sentence "Hello Friend" as opposed to each individual letter and storing each in a list?
Thanks in advance!
json1_text = [v for i in json_data for k,v in i.items() if isinstance(v,str)]
print (json1_text)
Result:
['Salam', 'Hello Friend']
Below is my requirement. Below is the data that is present in json file:
{"[a]":" text1","[b]":" text2","[a]":" text3","[c]":" text4","[c]":" Text5"}.
The final output should be like
{"[a]":[" text1","text3"],"[b]":" text2","[c]":" text4"," Text5"]}.
I tried below code:
data_in= ["[a]"," text1","[b]"," text2","[a]"," text3","[c]"," text4","[c]"," text5"]
data_pairs = zip(data_in[::2],data_in[1::2])
data_dict = {}
for x in data_pairs:
data_dict.setdefault(x[0],[]).append(x[1])
print data_dict
But the input it takes is more in form of List than a dictionary.
Please advise.
Or is there a way where i can convert my original dictionary into list with multiple values as list will take only unique values. Please let me know the code also i am very new to Python and still learning it. TIA.
Keys are unique within a dictionary while values may not be.
You can try
>>> l = ["[a]"," text1","[b]"," text2","[a]"," text3","[c]"," text4","[c]"," text5"]
>>> dict_data = {}
>>> for i in range(0,len(l),2):
if dict_data.has_key(l[i]):
continue
else:
dict_data[l[i]] = []
>>> for i in range(1,len(l),2):
dict_data[l[i-1]].append(l[i])
>>> print dict_data
{'[c]': [' text4', ' text5'], '[a]': [' text1', ' text3'], '[b]': [' text2']}
These are the contents of my text file (eg:abc.doc):
{'data': [{'name': 'abc'},{'name': 'xyz'}]}
After opening the file in python; how do i remove all the brackets, quotes and commas.
The final output should be:
data:
name:abc
name:xyz
Use ast.literal_eval() to turn it into a python structure, then print the values:
with open(r'd:\output1.doc', 'r') as inputfile:
inputstring = inputfile.read()
data = ast.literal_eval(inputstring)
for key, sublist in data.items():
print '{}:'.format(key)
for subdict in sublist:
for key, value in subdict.items():
print('{}:{}'.format(key, value))
For your example that results in:
>>> inputstring = "{'data': [{'name': 'abc'},{'name': 'xyz'}]}"
>>> import ast
>>> data = ast.literal_eval(inputstring)
>>> for key, sublist in data.items():
... print '{}:'.format(key)
... for subdict in sublist:
... for key, value in subdict.items():
... print '{}:{}'.format(key, value)
...
data:
name:abc
name:xyz
However: If you got this from the Facebook API, then you transcribed the format incorrectly. The Facebook API gives you JSON data, which uses double quotes (") instead:
{"data": [{"name": "abc"},{"name": "xyz"}]}
in which case you should use the json library that comes with Python:
import json
data = json.loads(inputstring)
# process the same way as above.
If you have a filename, you can ask the library to read straight from the file using:
data = json.load(filename) # note, no `s` after `load`.
Looks to me like you have json, which can be easily parsed using pyjson:
import json
obj=json.loads(u'''{'data': [{'name': 'abc'},{'name': 'xyz'}]}''')
Bob's your uncle now, innit?