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)
Related
from django.shortcuts import render
from django.http import HttpResponse
booksList = [
{ 'id' = '1',
'title' = "Beginner's Course in Django",
'description' = 'Foundational Course in Django'}
{ 'id' = '2',
'title' = "Intermediate Course in Django",
'description' = 'Next steps in Django'
},
{
'id' = '3',
'title' = "Advanced Course in Django",
'description' = 'The complexities of Django'
},
]
I am rendering data to a template using the above bookList and getting two errors:
'[' was not closed Pylance and
'{' was not closed Pylance
Kindly advise.
I have just found the error: colon (:) should be used in place of the equal sign (=).The following code works:
from django.shortcuts import render
from django.http import HttpResponse
booksList = [
{ 'id' : '1',
'title' : "Beginner's Course in Django",
'description' : 'Foundational Course in Django'},
{ 'id' : '2',
'title' : "Intermediate Course in Django",
'description' : 'Next steps in Django'
},
{
'id' : '3',
'title' : "Advanced Course in Django",
'description' : 'The complexities of Django'
},
]
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'
Suppose I have a List<map> that looks like this:
‘Books’:[
‘B1’{
‘id’: ’1234’,
‘bookName’: ’book1’
},
‘B2’{
‘id’: ’4567’,
‘bookName’: ’book2’
},
‘B3’{
‘id’: ’1234’,
‘bookName’: ’book3’
},
‘B4’{
‘id’: ’8912’,
‘bookName’: ’book4’
},
…
];
I’m trying to return the entire book without duplications in Id.
The expected result should be like this:
‘B1’{
‘id’: ’1234’,
‘bookName’: ’book1’
},
‘B2’{
‘id’: ’4567’,
‘bookName’: ’book2’
},
‘B4’{
‘id’: ’8912’,
‘bookName’: ’book4’
},
I guessed what your input map was and made a solution based on this answer from Basic Coder.
final list = {
'Books':[
{
'id':'1234',
'bookName':'book1'
},
{
'id':'4567',
'bookName':'book2'
},
{
'id': '1234',
'bookName':'book3'
},
{
'id': '8912',
'bookName':'book4'
},
]};
void main() {
print('With duplicates $list');
final ids = list['Books']!.map<String>((e) => e['id']!).toSet();
list['Books']!.retainWhere((Map x) {
return ids.remove(x['id']);
});
print('Without duplicates $list');
}
This code shows your input as the variable list, which seems to be what you were going for with your provided data. The code then obtains a list of each id of the book and removes duplicates by changing it to a Set. Then it only retains elements in the original list with those non-duplicate ids.
Remove the ! operators if you're not using null-safety.
Here's one inspired by Christopher's answer:
void main() {
var books = {
'B1': {
'id': '1234',
'bookName': 'book1',
},
'B2': {
'id': '4567',
'bookName': 'book2',
},
'B3': {'id': '1234', 'bookName': 'book3'},
'B4': {'id': '8912', 'bookName': 'book4'},
};
var seen = <String>{};
var kept = books.entries.where((me) => seen.add(me.value['id'] ?? 'OTHER'));
print(Map.fromEntries(kept));
}
I think it's a bit simpler, since it doesn't have to populate the Set first. I also learned that Set.add returns a bool to indicate the element didn't exist before. Nice.
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'}]
>>>
So I'm using request from https://github.com/request/request#forms. In tsx file, I'm passing
id: id, text: string, array: number[].
post(
{json: true, url: '...', form: {id: id, text: text, array: array}},
(error, response, body) => {
if (response.statusCode === 400) {
dispatch(errStep(body['text']));
} else {
dispatch(addStep(body));
}
}
)
This is a post method with the body {id: id, text: text, array: array}. However, from Django, when I print the request.data, I receive <QueryDict: {'text': ['hello'], 'id': ['12'], 'array[0]': ['51'], 'array[1]': ['52']}>.
This way, I can't retrieve the array ['51', '52] by calling request.data.getlist('array').
I would like my request.data to be in this format: <QueryDict: {'text': ['hello'], 'id': ['12'], 'array': ['51', '52']}> because [51, 52] is returned by calling request.data.getlist('array').
Thanks!
qsStringifyOptions: {arrayFormat: 'repeat'} as one of the options in post call will transform 'array[0]': ['51'] , 'array[1]': ['53'] to 'array': ['51', '52']