how print the function by the location in the list? - list

data = [
{
'name': 'Instagram',
'follower_count': 346,
'description': 'Social media platform',
'country': 'United States'
},
{
'name': 'Cristiano Ronaldo',
'follower_count': 215,
'description': 'Footballer',
'country': 'Portugal'
},
{
'name': 'Ariana Grande',
'follower_count': 183,
'description': 'Musician and actress',
'country': 'United States'
}]
def dictionary_value():
for value in data:
return value["name"], value["follower_count"],value["description"], value["country"]
Hi, I'm newbie in python and i have a question about dictionary and lists:
i would like that my function dictionary value() will return only the values and print the function by the location in the list, for example: if i want to choose data[2] the outcome should be: 'Ariana Grande', 183,'Musician and actress','United States'. i could not find a way to do it.

Use dict.values method:
def dictionary_value(i):
return list(data[i].values())
Output:
print(dictionary_value(2))
# 'Ariana Grande', 183,'Musician and actress','United States'

Related

request.data changes in every variable

I have this code:
initial_data = dict(request.data.copy())
reserve_data = dict(request.data.copy())
print(initial_data)
for key in initial_data.keys():
merchant_data = initial_data.get(key)
for sub_key in merchant_data.keys():
if sub_key in keys_to_change:
reserve_data[key].pop(sub_key)
reserve_data[key][values_to_change.get(sub_key)] = merchant_data.get(sub_key)
print(initial_data)
As you can see, I am not changing initial_data, but it changes anyway
#before
{'22': {'domain': 'cashier.random.io', 'salt': 'ewrwerwe', 'active': 1, 'separate_cashier': '', 'additional_hosts': {}, 'tradingroom_url': '', 'crm': {'login': '', 'secret': '', 'url': ''}, 'currencies': ['USD', 'EUR'], 'payment_methods': {'12': {}}, 'processors': {}}}
#after
{'22': {'salt': 'ewrwerwe', 'separate_cashier': '', 'additional_hosts': {}, 'tradingroom_url': '', 'crm': {'login': '', 'secret':
'', 'url': ''}, 'currencies': ['USD', 'EUR'], 'payment_methods': {'12': {}}, 'processors': {}, 'host': None, 'is_active': None}}
Is there a way to avoid this? Thanks everybody
initial_data = dict(request.data.copy())
reserve_data = dict(request.data.copy())
does shallow copies of the request data.
If you're internally modifying the contents, you'll need to use copy.deepcopy instead:
initial_data = dict(copy.deepcopy(request.data))
reserve_data = dict(copy.deepcopy(request.data))

Flask Admin - How to fix or eliminate a datepicker truncated

I have two datepickers for a date field. One truncated (flask_admin, I believe) and another is because the form_widget_args, as bellow:
form_widget_args = {
'date': {
'type': 'date',
'rows': 20
}
}
How can I eliminate or fix the truncated one?
Solved.
form_widget_args = {
'date': {
'type': 'date',
'autocomplete': 'off',
'data-role': '',
'rows': 20
}

Django Rest Framework - Envelope a Paginated Response

I want to wrap an paginated response in an envelope. The Result should look like this.
{
"data": ["datum 1", "datum 2", "datum 3"],
"meta": {
"some": "meta",
"data": "foo",
},
"page": {
"total": 12345,
"count": 3,
"from": 3,
"to": 6,
"next": "http://example.com?page=2",
"prev": "http://example.com?page=0",
}
}
The custom page format can be achieved by inheriting from PageNumberPagination.
My question is about passing the Metadata. I do not see any way to pass it to the Pagination except some form of in band signaling. Is there a clean(er) way to do this?
class CustomPagination(pagination.PageNumberPagination):
view = None
def paginate_queryset(self, queryset, request, view=None):
self.view = view
return super().paginate_queryset(queryset, request, view)
def get_meta(self, data=None, **meta):
return {
'data_from_view': self.view.__class__.__name__,
'static_data': settings.ROOT_URLCONF,
'len_per_page': len(data),
'dynamic_data_on_thy_fly': meta
}
def get_paginated_response(self, data, **meta):
return Response({
'links': {
'next': self.get_next_link(),
'previous': self.get_previous_link()
},
'meta': self.get_meta(data, **meta),
'count': self.page.paginator.count,
'results': data
})

python one liner for creating dictionary from list

I am learning dictionary comprehension, and wrote the following code.
The output of the list 'lines' looks like this:
[['Color', 'Blue', 'Model', 'Ford'], ['Color', 'Green', 'Model', 'Honder'], ['Color', 'Pink', 'Model', 'peugeot']]
'
#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python
import pprint
d={}
FILE='File.txt'
with open(FILE, 'r') as Data:
lines = [line.split() for line in Data ]
#print lines
for x in lines:
d[x[0]] = x[1]
d[x[2]] = x[3]
pprint.pprint(d)
Basically i am trying to figure out how i can convert the above for loop into a single line.
So far i tried the below code:
e = {x[0]:x[1] for x in lines}
But that would only give me the very last entry of the list.
Here's a clean solution using the third form of the dict constructor:
>>> from itertools import izip
>>> l=[['Color', 'Blue', 'Model', 'Ford'], ['Color', 'Green', 'Model', 'Honder'], ['Color', 'Pink', 'Model', 'peugeot']]
>>> [dict(izip(d[::2], d[1::2])) for d in l]
[{'Color': 'Blue', 'Model': 'Ford'}, {'Color': 'Green', 'Model': 'Honder'}, {'Color': 'Pink', 'Model': 'peugeot'}]
>>>

How to sort values in dictionaries

Below is the sample code snippet i want to sort
Variable books is a dictionaries contains values.
books = {
1234 : {
'isbn' : '1234',
'name' : 'Test Book 1',
'publish' : 'January 1990'
},
2345 : {
'isbn' : '2345',
'name' : 'Sample Book',
'publish' : 'December 2000'
}
}
for key, values in books.items():
values.sort(key=lambda x: int(x['name']))
When i compiled the code. I have an error encounntered. 'dict' object has no attribute 'sort'
How can I sort the books by values with the key 'name'
You need to create an OrderedDict from books, which is a dict that keeps track of the insertion order (like list). This module is sub class of dict, and has sorting functionality. You then can use
>>> OrderedDict(sorted(books.items(), key=lambda x: x[1]))
OrderedDict([(1234, {'isbn': '1234', 'name': 'Test Book 1', 'publish': 'January 1990'}), (2345, {'isbn': '2345', 'name': 'Sample Book', 'publish': 'December 2000'})])
If you don't need it to be a dict, you can use the sorted function and have list of tuples (with dicts inside the items)