from the given input
lists = ["7ee57f24", "deadbeef"]
I want to get the following output
l1': [
{
'd':
{
'id': '7ee57f24'
}
},
{
'd':
{
'id': 'deadbeed'
}
}
]
I have tried this code
lists = ["7ee57f24", "deadbeef"]
l1 = {"d":[{"id": lis} for lis in lists]}
print(l1)
but it gives me wrong output
{'d': [{'id': '7ee57f24'}, {'id': 'deadbeef'}]}
Use the following:
lists = ["7ee57f24", "deadbeef"]
l1 = [
{"d": {"id": id_}}
for id_ in lists
]
print(l1)
Output:
[{'d': {'id': '7ee57f24'}}, {'d': {'id': 'deadbeef'}}]
Related
Hi i have an array of objects like below,
"output": [
{
'id': 1,
'items': [
{
'id':'1',
'data': {
'id': 3,
}
},
{
'id': '2',
'data': {
'id': 4,
}
}
]
},
{
'id': 2,
'items': [
{
'id':'3',
'data': {
'id': 5,
}
},
]
},
]
I want to retrieve the id property of items array and put it an array so the expected output is ['1','2','3']
below code works in javascript
arr_obj.map(obj=>obj.items.map(item=>item.id)).flat()
how can i do the above in python and django. could someone help me with this. I am new to python and django thanks.
Edit:
An example of how the logging the data in console looks.
output '[{'id': 1,'items': [{'id': 14, 'data': {'id': 1,}],}]'
You can work with list comprehension:
>>> [i['id'] for d in data for i in d['items']]
['1', '2', '3']
where data is the list of dictionaries.
I have source_json data looking like this:
{
'ID': {
'0': 8573273,
'1': 8573277
},
'prediction': {
'0': 4.411029362081518,
'1': 4.411029362081518
},
'feature': {
'0': 0,
'1': 0
}
}
But I need it to be in this form:
[
{
'ID': 8573273,
'prediction': 4.411029362081518,
'feature': 0
},
{
'ID': 8573277,
'prediction': 4.411029362081518,
'feature': 0
}
]
I convert the first view to Pandas dataframe and then convert it to the desirable json.
t = pd.DataFrame(source_json)
proper_jsone = t.to_dict(orient='records')
The question is: Is there a proper way to do this without creating an additional dataframe?
I prefer traditional way:
all_keys = list(source_json.keys())
all_indices = list(source_json[all_keys[0]].keys())
transformed_json = [ {_k:source_json[_k][_idx] for _k in all_keys} for _idx in all_indices]
You can try list comprehension
[{'ID':i, 'prediction':j, 'feature':k}
for i,j,k in zip(*[i.values() for i in d.values()]) ]
output
[{'ID': 8573273, 'prediction': 4.411029362081518, 'feature': 0},
{'ID': 8573277, 'prediction': 4.411029362081518, 'feature': 0}]
1) How we can combine a dict with list and return the result as JSON?
Have tried to combine list_1(dict) and list_2(list), but getting error. Also, after converting them to strings can combine but could not decode back to JSON format(as expected result below).
2) Also, how to replace a value within JSON and maintain it as JSON?
list_1 = [{'title': 'NEWBOOK', 'downloads': '4', 'views': '88'}]
list_2 = {'title': 'MASTERMIND', 'downloads': '16', 'views': '156'}
list_3 = {
'a': 'b',
'c': 'd',
'e': [{
'f': 'g',
'l': 'm'
}]
}
Script which I have tried as below.
combine = list_1 + list_2
for z in list_3['e']:
list_3 = list_3.replace(z, combine)
Expected_json = json.dumps(list_3)
print(list_3)
Error1:
combine = list_1 + list_2
TypeError: can only concatenate list (not "dict") to list
Error2:
list_3 = list_3.replace(z, combine)
AttributeError: 'dict' object has no attribute 'replace'
Expected result:
list_3 = {
"a": "b",
"c": "d",
"e": [{
"f": "g",
"l": "m"
},
{
"title": "NEWBOOK",
"downloads": "4",
"views": "88"
},
{
"title": "MASTERMIND",
"downloads": "16",
"views": "156"
}
]
}
Simply append to the list in the dictionary
list_3['e'].append(list_2)
list_3['e'].append(list_1[0])
print(list_3)
{
'a':
'b',
'c':
'd',
'e': [{
'f': 'g',
'l': 'm'
}, {
'title': 'MASTERMIND',
'downloads': '16',
'views': '156'
}, {
'title': 'NEWBOOK',
'downloads': '4',
'views': '88'
}]
}
import json
list_1 = [{'title': 'NEWBOOK', 'downloads': '4', 'views': '88'}]
list_2 = {'title': 'MASTERMIND', 'downloads': '16', 'views': '156'}
list_3 = {
'a': 'b',
'c': 'd',
'e': [{
'f': 'g',
'l': 'm'
}]
}
list_3['e'].append(list_1[0])
list_3['e'].append(list_2)
json_list = json.dumps(list_3)
if you want to add more lists to the location you do the following
b= json.loads(json_list)
b['e'].append(your_new_dict)
json_list = json.dumps(b)
if you have no idea what list_1 and list_2 are then you can test for the class type and append them accordingly. Like
if(type(list_1)==list):
list_3['e'].append(list_1[0])
if(type(list_2)==dict):
list_3['e'].append(list_2)
if you dont know at which point in list_3 you want to append the list. you do something like the following. Assuming there is only one list in list_3
for x in list_3.values():
if(type(x)==list):
x.append(list_1[0])
x.append(list_2)
I have this code...it works, but is there a better way to do it?
So if the participant list is [ { 'Id': 5, 'name':'bob'}, {'Id': 4, 'name': 'sally'} ], result should be '5, 4'.
participant_list = obj['participants']
id_num = []
for participant in participant_list:
id_num.append(str(participant['Id']))
result = ",".join(id_num)
Use a list comprehension with str.join:
>>> participant_list = [ { 'Id': 5, 'name':'bob'}, {'Id': 4, 'name': 'sally'} ]
>>> ", ".join([str(p["Id"]) for p in participant_list])
'5, 4'
>>>
Using map(), This works -
>>> participant = [ { 'Id': 5, 'name':'bob'}, {'Id': 4, 'name': 'sally'} ]
>>> ",".join(map(lambda x: str(x['Id']), participant))
'5,4'
How about:
>>> ','.join([str(i['Id']) for i in participant_list])
'5,4'
If I have a dictionary, which contains lists, dictionaries, strings, and integers, how can I copy that dictionary, but only specific white listed keys?
Filtering old_dict through this function would give me new_dict. The white listed keys can be in whatever format, but the solution should be able to take an object of arbitrary white listed keys to produce the output.
old_dict = [
{
'name': {'first': "John", 'last': "Doe"},
'groups': ["foo", "bar"],
'widgets': [
{'id': 0, 'name': "Acme"},
{'id': 1, 'name': "Anvil"},
],
},
{
'name': {'first': "David"},
'groups': ["bar", "bash", "ding"],
'widgets': [
{'id': 1, 'name': "Anvil"},
{'id': 8, 'name': "Bingo"},
],
},
]
new_dict = [
{
'name': {'last': "Doe"},
'widgets': [
{'name': "Acme"},
{'name': "Anvil"},
],
},
{
'name': { },
'widgets': [
{'name': "Anvil"},
{'name': "Bingo"},
],
},
]
new_dict = []
for dic in old_dic:
new_dict.append({})
for key in white_list: #list of keys
if key in dic:
new_dict[key] = old_dic[key]
Which you can make in to a list comprehension as:
new_dic = [ dict( key, old_dic[key])
for key in whitelist
if key in old_dic)
for dic in old_dic ]
Make a recursive function that handles each type and filters out whenever you see a dict:
def keep_only(keys, val):
if type(val) is list:
return [keep_only(keys, v) for v in val]
if type(val) is dict:
return dict((k, keep_only(keys, v)) for k,v in val.items() if k in keys)
return val
Sample usage:
>>> old_dict = [
{
'name': {'first': "John", 'last': "Doe"},
'groups': ["foo", "bar"],
'widgets': [
{'id': 0, 'name': "Acme"},
{'id': 1, 'name': "Anvil"},
],
},
{
'name': {'first': "David"},
'groups': ["bar", "bash", "ding"],
'widgets': [
{'id': 1, 'name': "Anvil"},
{'id': 8, 'name': "Bingo"},
],
},
]
>>> keep_only(set(['name', 'widgets', 'last']), old_dict)
[{'widgets': [{'name': 'Acme'}, {'name': 'Anvil'}], 'name': {'last': 'Doe'}}, {'widgets': [{'name': 'Anvil'}, {'name': 'Bingo'}], 'name': {}}]