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'}]
>>>
Related
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'
I'm trying to plot a graph from the database by using axios endpoint to get the data. I suspect it has something to do with the format. As I can see still see the correct data when navigating to api/chart/data/.
I have two variables, one is working fine but another is undefined:
total_km and sorted_vehicle_list
so when I console.log(labels), it said "Error Cannot read property 'hidden' of undefined"
P.S. sorted_vehicle_list has one only instance and returns as a list [] (which I'm sure if it's the problem)
I have tried to print the output of the query in views.py and the output is correct. It returns the data that I want but somehow Chart.js can't see it.
class ChartData(APIView):
authentication_classes = []
permission_classes = []
def get(self, request, format=None):
all_vehicles = LoggerRecord.objects.values('imei').distinct()
vehicle_list = []
for vehicle in all_vehicles:
vehicle_list.append(vehicle['imei'])
sorted_vehicle_list = sorted(vehicle_list)
#create sum km
total_km = LoggerRecord.objects.aggregate(Sum('distance'))
print(total_km)
print(all_vehicles)
data = {
'all_vehicles': all_vehicles,
'total_km': total_km
}
return Response(data)
axios.get(endpoint)
.then(function (response) {
labels = response.data.sorted_vehicle_list
total_km = response.data.total_km
console.log(labels)
console.log(total_km)
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx2, {
// The type of chart we want to create
type: 'bar',
// The data for our dataset
data: {
labels: labels,
datasets: [{
label: 'Total KM',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: total_km
}]
}
//console.log(response);
})
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)
Django 1.10.
https://docs.djangoproject.com/en/1.10/topics/forms/formsets/#can-order
https://docs.djangoproject.com/en/1.10/topics/forms/formsets/#can-delete
The examples at both of the abovementioned links are as follows:
>>> data = {
... 'form-TOTAL_FORMS': '3',
... 'form-INITIAL_FORMS': '2',
... 'form-MAX_NUM_FORMS': '',
... 'form-0-title': 'Article #1',
... 'form-0-pub_date': '2008-05-10',
... 'form-0-DELETE': 'on',
... 'form-1-title': 'Article #2',
... 'form-1-pub_date': '2008-05-11',
... 'form-1-DELETE': '',
... 'form-2-title': '',
... 'form-2-pub_date': '',
... 'form-2-DELETE': '',
... }
>>> formset = ArticleFormSet(data, initial=[
... {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},
... {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
... ])
What troubles me: why should we need initial data here? It overburdens the documentation as we don't use the initial data in the example. The only case when we need both data and initial is when we use has_changed().
I'm a newbie. Maybe I don't understand that deep.
How do you think, maybe I should draw the attention of the community at Djangoproject to this problem?
So, I have this, for example:
['Apple', 'Red', 'Banana', 'Yellow']
and I need to return
{'Apple': 'Red', 'Banana': 'Yellow'}
Is there a way to do this?
Just slice the list and use dict :
>>> li=['Apple', 'Red', 'Banana', 'Yellow']
>>> dict((li[:2],li[2:]))
{'Apple': 'Red', 'Banana': 'Yellow'}
If it's a list like [k1, v1, k2, v2, ...] just use slicing and zip:
>>> l = ['Apple', 'Red', 'Banana', 'Yellow']
>>> dict(zip(l[::2], l[1::2]))
{'Banana': 'Yellow', 'Apple': 'Red'}
Like this you first create two list, one containing the keys, the other containing the values:
>>> k, v = l[::2], l[1::2]
>>> k
['Apple', 'Banana']
>>> v
['Red', 'Yellow']
Then zip creates an iterator of tuples (pairs of key and value in this case):
>>> list(zip(k, v))
[('Apple', 'Red'), ('Banana', 'Yellow')]
This iterator then can be used to create the dictionary.
For Python 3.x you can just use the dict comprehension syntax
d = {key: value for (key, value) in item}
you can use the item in any way you want.