Check if a set of key/values in dict list is in another list - list

I have a list as follows:
[
{
'Name': 'Name1',
'Address': 'Address1'
},
{
'Name': 'Name2',
'Postcode': 'MyPostcode'
}
]
And another list like this:
[
{
'Name': 'Name1',
'data' : {
'Address': 'Address1',
'Postcode': 'Whatever'
},
{
'Name': 'Name2',
'data' : {
'Address': 'Whatever',
'Postcode': 'MyPostcode'
},
{
'Name': 'Name3',
'data' : {
'Address': 'Whatever',
'Postcode': 'Whatever'
},
]
For any of the items in the first list, I need to check if that combination of key/value exists in the second, and if so, delete it from the second
I can do it in multiple lines of codes, with different for loops, but probably there is a wiser way of doing it. Can anybody suggest an elegant solution?
In the example above, it should delete the two first dicts from the list and return a list only with the third one
[
{
'Name': 'Name3',
'data' : {
'Address': 'Whatever',
'Postcode': 'Whatever'
}
]
Thanks

Try:
lst1 = [
{"Name": "Name1", "Address": "Address1"},
{"Name": "Name2", "Postcode": "MyPostcode"},
]
lst2 = [
{"Name": "Name1", "data": {"Address": "Address1", "Postcode": "Whatever"}},
{
"Name": "Name2",
"data": {"Address": "Whatever", "Postcode": "MyPostcode"},
},
{"Name": "Name3", "data": {"Address": "Whatever", "Postcode": "Whatever"}},
]
out = []
for d2 in lst2:
t = set({"Name": d2["Name"], **d2["data"]}.items())
for d1 in lst1:
if t.issuperset(d1.items()):
break
else:
out.append(d2)
print(out)
Prints:
[{'Name': 'Name3', 'data': {'Address': 'Whatever', 'Postcode': 'Whatever'}}]

Related

How to set dynamic attributes in django rest framework serializers?

I have some json in the following format:
{
"daySchedules": {
"500000004061582000": {
"scheduleName": "Friday-Sunday",
"services": [
{
"name": "Lunch",
"hours": {
"startTime": "12:00:00.000",
"endTime": "16:00:00.000"
},
"overnight": false
},
{
"name": "Dinner",
"hours": {
"startTime": "17:00:00.000",
"endTime": "23:00:00.000"
},
"overnight": false
}
],
"openTime": "12:00:00.000",
"closeTime": "23:00:00.000"
},
"500000004061559163": {
"scheduleName": "Tuesday-Thursday",
"services": [
{
"name": "Breakfast",
"hours": {
"startTime": "04:00:00.000",
"endTime": "11:00:00.000"
},
"overnight": false
},
{
"name": "Lunch",
"hours": {
"startTime": "12:00:00.000",
"endTime": "16:00:00.000"
},
"overnight": false
},
{
"name": "Dinner",
"hours": {
"startTime": "17:00:00.000",
"endTime": "20:00:00.000"
},
"overnight": false
}
],
"openTime": "04:00:00.000",
"closeTime": "20:00:00.000"
}
},
"weekSchedule": {
"monday": null,
"tuesday": "500000004061559163",
"wednesday": "500000004061559163",
"thursday": "500000004061559163",
"friday": "500000004061582000",
"saturday": "500000004061582000",
"sunday": "500000004061582000"
}
}
The attributes in the json 500000004061582000 and 500000004061559163 is dynamic and determined by what's returned in the weekSchedule.
I wish to create the following serializers:
class ScheduleForDaySerializer(serializers.Serializer):
schedule_name = serializers.CharField()
services = serializers.ListField()
open_time = serializers.CharField()
close_time = serializers.CharField()
class WeekScheduleSerializer(serializers.Serializer):
monday = serializers.CharField(allow_null=True)
tuesday = serializers.CharField(allow_null=True)
wednesday = serializers.CharField(allow_null=True)
thursday = serializers.CharField(allow_null=True)
friday = serializers.CharField(allow_null=True)
saturday = serializers.CharField(allow_null=True)
sunday = serializers.CharField(allow_null=True)
class DaySchedulesSerializer(serializers.Serializer):
# what comes here?
class SchedulesSerializer(serializers.Serializer):
day_schedules = DaySchedulesSerializer()
week_schedule = WeekScheduleSerializer()
I'm struggling to determine how to serialize the attributes for that daySchedules json object since the key attributes are dynamic and not necessarily the same each time. Ideally I want to explicitly list out what each attribute type is.
After creating the serializer I want to do the following:
serializer = SchedulesSerializer(data=data) # data is the json object shown above
serializer.is_valid()
response = serializer.data
# do something with the response

Dart/Flutter - How to delete key-value-pairs of element of Map inside a List?

How can I can delete a specific key-value-pair in that type of List<Map<String, dynamic>> for each map.
For example:
List<Map<String, dynamic>> before the operation:
List<Map<String, dynamic>> currencies = [
{
'id': 1,
'name': 'coin',
'desc': 'This is just a blindtext.',
'order': 101,
'icon': 'https://icon1.jpg'
},
{
'id': 2,
'name': 'karma',
'desc': 'This is just a blindtext.',
'order': 102,
'icon': 'https://icon2.jpg'
},
{
'id': 3,
'name': 'laurel',
'desc': 'This is just a blindtext.',
'order': 104,
'icon': 'https://icon3.jpg'
},
];
List<Map<String, dynamic>> after the operation I am searching for:
List<Map<String, dynamic>> currencies = [
{
'id': 1,
'name': 'coin',
'icon': 'https://icon1.jpg'
},
{
'id': 2,
'name': 'karma',
'icon': 'https://icon2.jpg'
},
{
'id': 3,
'name': 'laurel',
'icon': 'https://icon3.jpg'
},
];
So basically, I deleted "unwanted" key-value-pairs.
Any suggestions?
Thanks in advance!!
currencies.forEach((item) => item..remove("order")..remove("desc"));

format dictionary using python

I am new to python, can someone tell me how can we change the given code into the formatted code given below .
The data is stored in a dictionary and i want to store the formatted data also in a dictionary.
I am using python version 2.7.
Is it possible to do the same?
Can the alterations be made in the same dictionary or we need to create a new dictionary?
The code I have :
{
"roles":
{
"AA":[
{
"date":"20150101",
"total":6.0
},
{
"date":"20150201",
"total":14.5
},
{
"date":"20150301",
"total":14.5
}
],
"AB":[
{
"date":"20150301",
"total":1.6
},
{
"date":"20150401",
"total":1.6
},
{
"date":"20150501",
"total":7.24
}
]
}
}
The code I want :
{
"key" : "roles",
"values" : [
{
"key": "AA",
"values": [
{
"date": "20150101",
"total": 6
},
{
"date": "20150201",
"total": 14.5
},
{
"date": "20150301",
"total": 14.5
}
]
},
{
"key": "AB",
"values": [
{
"date": "20150301",
"total": 1.6
},
{
"date": "20150401",
"total": 1.6
},
{
"date": "20150501",
"total": 7.24
}
]
}
]
}
Not necessarily the most robust but gets the job done as long as the input format stays consistent with the example you provided (using pprint only for formatted output. You don't have to install it for the code to work)
from pprint import pprint
output = {}
for key, value in input_dict.items():
output['key'] = key
output['values'] = [{'key': inner_key, 'values': inner_value}
for inner_key, inner_value in value.items()]
pprint(output)
Outputs
{'key': 'roles',
'values': [{'key': 'AA',
'values': [{'date': '20150101', 'total': 6.0},
{'date': '20150201', 'total': 14.5},
{'date': '20150301', 'total': 14.5}]},
{'key': 'AB',
'values': [{'date': '20150301', 'total': 1.6},
{'date': '20150401', 'total': 1.6},
{'date': '20150501', 'total': 7.24}]}]}

Facebook Messenger Bot - Invalid URL button fields for List Template

I have been working to send a list to user containing some data. I am following facebook's doc to setup my request payload. However, I am getting the following error:
{'error': {
'message': '(#100) Invalid URL button fields provided. Please check documentation for details.',
'type': 'OAuthException',
'code': 100,
'error_subcode': 2018125, 'fbtrace_id': 'GZFFcM+j5e/'}}
Here is my JSON Payload:
{'recipient': {'id': 'MY_MESSENGER_ID'},
'message':
{'attachment':
{'type': 'template',
'payload':
{'template_type': 'list',
'top_element_style': 'compact',
'elements':
[{'title': 'Hello 1', 'subtitle': 'Subtitle 1',
'buttons':
[{'title': 'View', 'type': 'web_url',
'url': 'https://www.medium.com/',
'messenger_extensions': 'false',
'webview_height_ratio': 'full',
'fallback_url': 'https://www.medium.com/'}],
'default_action':
{'title': 'View', 'type': 'web_url',
'url': 'https://www.medium.com/',
'messenger_extensions': 'false',
'webview_height_ratio': 'full',
'fallback_url': 'https://www.medium.com/'}},
{'title': 'Hello 2', 'subtitle': 'Subtitle 2',
'image_url': 'https://cdn-images-1.medium.com/1*Vkf6A8Mb0wBoL3Fw1u0paA.jpeg',
'buttons':
[{'title': 'View', 'type': 'web_url',
'url': 'https://www.medium.com/',
'messenger_extensions': 'false',
'webview_height_ratio': 'full',
'fallback_url': 'https://www.medium.com/'}],
'default_action':
{'title': 'View', 'type': 'web_url',
'url': 'https://www.medium.com/',
'messenger_extensions': 'false',
'webview_height_ratio': 'full',
'fallback_url': 'https://www.medium.com/'}}]}}}}
I have checked, re-checked it multiple times. PLUS, I have sent the facebook's example json from the doc but I have got the same reply. Please take a look and let me know where I am stuck!
This is my end url:
"https://graph.facebook.com/v2.6/me/messages?access_token="
Thanks in advance!
Your request has two issues:
For default_action, you can set fallback_url only if messenger_extensions:true
default_action cannot have a title prop.
Try this:
{
"recipient": {
"id": "{{PSID}}"
},
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "list",
"top_element_style": "compact",
"elements": [{
"title": "Hello 1",
"subtitle": "Subtitle 1",
"buttons": [{
"title": "View",
"type": "web_url",
"url": "https://www.medium.com/",
"messenger_extensions": "false",
"webview_height_ratio": "full"
}],
"default_action": {
"type": "web_url",
"url": "https://www.medium.com/",
"messenger_extensions": "false",
"webview_height_ratio": "full"
}
},
{
"title": "Hello 2",
"subtitle": "Subtitle 2",
"image_url": "https://cdn-images-1.medium.com/1*Vkf6A8Mb0wBoL3Fw1u0paA.jpeg",
"buttons": [{
"title": "View",
"type": "web_url",
"url": "https://www.medium.com/",
"messenger_extensions": "false",
"webview_height_ratio": "full"
}],
"default_action": {
"type": "web_url",
"url": "https://www.medium.com/",
"messenger_extensions": "false",
"webview_height_ratio": "full"
}
}
]
}
}
}
}

How to nest a serializer?

So I'm trying to create an /api/info url that return various data on my application. It pulls data from various models and puts it together in one response. I got the following:
class SessionInfo(generics.GenericAPIView):
def get(self, request, format=None):
token = Token.objects.get(user=self.request.user)
userprofile = UserProfile.objects.get(user=self.request.user)
is_admin = self.request.user.is_staff
is_primary_owner = userprofile.primary_owner
managers = userprofile.reports_to.all()
man = ["test manager 1", "test manager 2"]
pages = Page.objects.filter(published=True, show_in_menu=True)
pages_output = JSONRenderer().render(PageSerializer(pages).data)
content = {
'user': {
"username": str(self.request.user.username),
"first_name": str(self.request.user.first_name),
"last_name": str(self.request.user.last_name),
"is_admin": is_admin,
"is_primary_owner": is_primary_owner,
"api_token": token.key,
"timezone": 'blalala',
"managers": man,
},
'license': {
"plan" : "gold",
"expiry_date" : "lol",
},
'feature_flags': {
'billing_test': False,
},
'pages': { pages_output },
}
return Response(content)
However it doesn't properly serialize and render pages, making it an escaped string instead:
{
"feature_flags": {
"billing_test": false
},
"user": {
"username": "test#user.com",
"first_name": "Test",
"last_name": "User",
"is_admin": true,
"managers": [
"test manager 1",
"test manager 2"
],
"api_token": "08d1a5827da9a90e7746949ffd2e69e87c51b272",
"timezone": "blalala",
"is_primary_owner": false
},
"license": {
"expiry_date": "lol",
"plan": "gold"
},
"pages": [
"[{\"id\": 1, \"title\": \"Trololol\"}, {\"id\": 2, \"title\": \"NEW pages\"}]"
]
}
if I use directuly use pages_output = PageSerializer(pages) I get:
<webapp_api_v1.serializers.PageSerializer object at 0x10a0d8f90> is not JSON serializable
How can I make a serializer properly nest within my constructed response? Thanks!
Solved it with pages_output = PageSerializer(pages).data and changing 'pages': pages_output,