This question already has answers here:
How do I sort a dictionary by key?
(32 answers)
Closed 5 years ago.
I'm having trouble sorting my dictionary alphabetically by its keys.
Here's my code:
colorSizes = {'Rust': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16', 'SIZE 18'],
'Middle Blue': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16', 'SIZE 18'],
'Grey': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16', 'SIZE 18'],
'Aqua': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16', 'SIZE 18'],
'Navy': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16']}
realColor = {}
for key in sorted(colorSizes.keys()):
realColor[key] = colorSizes.get(key)
print(realColor)
What I get:
{'Yellow/Fuschia':['Large', 'Extra Large'],
'Black':['Small', 'Medium', 'Large']}
What I wanna get:
{'Black':['Small', 'Medium', 'Large'], 'Yellow/Fuschia':['Large', 'Extra Large']}
Thanks!
Dictionaries in python versions < 3.6 are unordered, sorting and reinserting is meaningless.
As a fix, either
Switch to python3.6 (keep in mind the caveats), or
Use an OrderedDict
For the second option, replace realColor = {} with a collections.OrderedDict:
from collections import OrderedDict
realColor = OrderedDict()
Here's an example of how an OrderedDict remembers the order of insertion:
dict1 = {}
dict1['k'] = 1
dict1['aSDFDF'] = 1234
print(dict1) # {'aSDFDF': 1234, 'k': 1}
from collections import OrderedDict
dict2 = OrderedDict()
dict2['k'] = 1
dict2['aSDFDF'] = 1234
print(dict2) # OrderedDict([('k', 1), ('aSDFDF', 1234)])
The __repr__ might be different, but the latter is still a dictionary and can be used accordingly.
Related
I need your help:
I want to create a list looking like this ['Unnamed: 16', 'Unnamed: 17', 'Unnamed:18'] for a range (16,60). How can I proceed?
I don't know if my question is clear but it's like doing list(range(16, 60) but with a string before each numbers.
Thank you very much for your help!!
You can use f-strings to do so :
my_list = [f"Unnamed: {i}" for i in range(16, 60)]
# Output
['Unnamed: 16', 'Unnamed: 17', 'Unnamed: 18', 'Unnamed: 19', ...]
I would do it following way
prefix = "Unnamed: "
lst = [prefix + str(i) for i in range(16,25)]
print(lst)
output
['Unnamed: 16', 'Unnamed: 17', 'Unnamed: 18', 'Unnamed: 19', 'Unnamed: 20', 'Unnamed: 21', 'Unnamed: 22', 'Unnamed: 23', 'Unnamed: 24']
Note: I used othre range for brevity sake. You might elect to use one of string formatting method instead.
You can do it using map as,
list(map(lambda x: f'Unnamed: {x}', range(16, 60)))
You can use f strings
name = 'Unamed:'
list = [f"{prefix} {i}" for i in range(16, 60)]
print(list)
my_list = []
for i in range(16, 60):
my_list.append("Unnamed: " + str(i))
print(my_list)
I am having trouble understanding key parameter in sorted function in Python.
Let us say, the following list is given: sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15'] and I would like to sort only the strings that contain number.
Expected output: ['Date ', 'of', 'birth', 'month 10', 'day 15', 'year 1990']
Until now, I only managed to print the string with the number
def sort_with_key(element_of_list):
if re.search('\d+', element_of_list):
print(element_of_list)
return element_of_list
sorted(sample_list, key = sort_with_key)
But how do I actually sort those elements?
Thank you!
We can try sorting with a lambda:
sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15']
sample_list = sorted(sample_list, key=lambda x: int(re.findall(r'\d+', x)[0]) if re.search(r'\d+', x) else 0)
print(sample_list)
This prints:
['Date ', 'of', 'birth', 'month 10', 'day 15', 'year 1990']
The logic used in the lambda is to sort by the number in each list entry, if the entry has a number. Otherwise, it assigns a value of zero to other entries, placing them first in the sort.
If I understand correctly, you want strings with a number to be sorted with this number as key, and strings without a number to be at the beginning?
You need a key that extracts the number from the string. We can use str.isdigit() to extract digits from a string, ''.join() to put these digits back together, and int() to convert to an integer. If there are no digits in the string, we'll return -1 instead, so it comes before all nonnegative numbers.
sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15', 'answer 42', 'small number 0', 'large number 8676965', 'no number here']
sample_list.sort(key=lambda s: int(''.join(c for c in s if c.isdigit()) or -1))
print(sample_list)
# ['Date ', 'of', 'birth', 'no number here', 'small number 0', 'month 10', 'day 15', 'answer 42', 'year 1990', 'large number 8676965']
I want to know how many times a sublist is in a list next to eachother.
From another question, I received the following code to determinate if a sublist is in a list:
list_sequence = ['Example 64', 'Example 32', 'Example 16']
my_list = ['Example 128', 'Example 64', 'Example 32', 'Example 16', 'Example 256', 'Example 512', 'Example 1024']
print(str(list_sequence)[1:-1] in str(my_list))
But I want to know, how many times the list_sequence is NEXT to each other to determinate a combo. In the top example its 1, but if I would append list_sequence at the start and at the very end, it still would 1. If I would add it right after Example 16 in my_list, it would be 2.
You can use zip and enumerate within a list comprehension to find the respective indices of places where your sub_list occurs. Then select those who's subtraction is equal to 3 (length of sub_list):
In [6]: list_sequence = ['Example 64', 'Example 32', 'Example 16']
...:
...: my_list = ['Example 128', 'Example 64', 'Example 32', 'Example 16', 'Example 64', 'Example 32', 'Example 16', 'Example 256', 'Example 512', 'E
...: xample 1024','Example 64', 'Example 32', 'Example 16']
...:
In [7]: indices = [index for index, (i, j, k) in enumerate(zip(my_list, my_list[1:], my_list[2:])) if list_sequence == [i, j, k]]
Out[7]: [1, 4, 10]
In [8]: sum(2 * (j-i == len(list_sequence)) for i, j in zip(indices, indices[1:]))
Out[8]: 2
You an only use a generator expression within sum to find the number of occurrences:
In [4]: sum(list_sequence == [i, j, k] for i, j, k in zip(my_list, my_list[1:], my_list[2:]))
Out[4]: 1
But note that this will also include overlaps because zip(my_list, my_list[1:], my_list[2:])) will give you all consequent triples.
Count By creating dictionary of list_sequence
list_sequence = ['Example 64', 'Example 32', 'Example 16']
my_list = ['Example 128', 'Example 64', 'Example 32', 'Example 16','Example 16', 'Example 256', 'Example 512', 'Example 1024']
dic=dict()
for i in list_sequence :
for j in my_list :
if i==j:
dic[i]=dic.get(i,0)+1
print(dic)
{'Example 64': 1, 'Example 32': 1, 'Example 16': 2}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a list that looks like this:
['Blake 4', 'Bolt 1', 'De Grasse 3', 'Gatlin 2', 'Simbine 5', 'Youssef Meite 6']
I am trying to print this:
Blake
Bolt
De Grasse
Gatlin
Simbine
Youssef Meite
How do I go about writing a list comprehension that handles this scenario? I tried using split and indexing but nothing I have used has worked.
Assuming all the values keep that pattern, split and join back, ignoring last value in splitted array:
l = ['Blake 4', 'Bolt 1', 'De Grasse 3', 'Gatlin 2', 'Simbine 5', 'Youssef Meite 6']
for x in l:
print(' '.join(x.split()[:-1]))
Otherwise, use regex to eliminate numerals:
import re
l = ['Blake 4', 'Bolt 1', 'De Grasse 3', 'Gatlin 2', 'Simbine 5', 'Youssef Meite 6']
for x in l:
print(re.sub(' \d+', '', x))
list comprehension is useless to print stuff (or any operations where you don't need the return value).
In your case, you could use str.rpartition in a loop to print only the left hand of the rightmost space found in the string:
l =['Blake 4', 'Bolt 1', 'De Grasse 3', 'Gatlin 2', 'Simbine 5', 'Youssef Meite 6']
for s in l:
print(s.rpartition(" ")[0])
Just stripping the last digit off the list would be a good usage of listcomp:
newl = [s.rpartition(" ")[0] for s in l]
Try this:
l = ['Blake 4', 'Bolt 1', 'De Grasse 3', 'Gatlin 2', 'Simbine 5', 'Youssef Meite 6']
for i in l:
print(i[:-2])
Indexing is sufficient for solving your problem.
Based on #Jean-François 's comment, if you are trying to remove all the characters before the last space, you can do this instead:
l = ['Blake 4', 'Bolt 1', 'De Grasse 3', 'Gatlin 2', 'Simbine 5', 'Youssef Meite 6']
for i in l:
print(i[:-i[::-1].index(' ')-1])
Given the list puzzle above, I need to be able to swap the position of X to left, right, top or bottom. The question is, how do I swap it with the item beside or in the other list in the list puzzle?
puzzle = [[' 1', ' 2', ' 3', ' 4'],
[' 5', ' 6', ' 7', ' 8'],
[' 9', '10', '11', '12'],
['13', '14', '15', ' X']]
#generic swap puzzle[a][b] with puzzle[c][d]
puzzle[a][b], puzzle[c][d] = puzzle[c][d], puzzle[a][b]