How to Convert Python Lists to Dictionaries and Sort by Weight Efficiently
This article demonstrates how to convert a Python list into a dictionary, sort the resulting mapping by numeric weight values (handling both 't' and 'kg' units), and extends the technique to nested lists and back‑to‑list conversions, providing multiple code solutions and explanations.
Introduction
Hello, I'm PiPi. I recently saw an interesting question on Zhihu and decided to share the solution.
Implementation
The problem involves converting a list to a dictionary and then sorting the dictionary by the numeric values of its entries, which may be expressed in tons ('t') or kilograms ('kg').
Basic conversion example:
d = ['熊', '1.3t', '海鸥', '88kg', '彭', '99kg', '凤', '0.68t']
rs = {d[i]: d[i+1] for i in range(0, len(d), 2)}
print(rs)To sort the dictionary by weight, one approach is:
dict1 = {'熊': '1.3t', '海鸥': '88kg', '彭': '99kg', '凤': '0.68t'}
list1 = []
for i, j in dict1.items():
list1.append([i, j])
print(list1)
def getWeight(weight):
if weight[-1] == 't':
return float(weight[:-1]) * 1000
elif weight[-2:] == 'kg':
return float(weight[:-2])
return 0
animals = sorted(list1, key=lambda animal: getWeight(animal[1]))
print(animals)More concise solutions were contributed by other users, for example:
d = ['熊', '1.3t', '海鸥', '88kg', '彭', '99kg', '凤', '0.88t']
d1 = dict(sorted(zip(d[::2], d[1::2]), key=lambda x: float(x[1].replace('t',''))*1000 if 't' in x[1] else float(x[1].replace('kg',''))))
print(d1)For nested list structures, the conversion and sorting can be performed as follows:
animals = [['熊', '1.3t'], ['海鸥', '88kg'], ['彭', '99kg'], ['凤', '0.68t']]
animals_dict = dict(animals)
print(animals_dict)
d1 = list(animals_dict.items())
d1.sort(key=lambda x: float(x[1][:-1])*1000 if '.' in x[1] else int(x[1][:-2]))
print(dict(d1))Finally, converting a dictionary back to a list of pairs:
dict1 = {'熊': '1.3t', '海鸥': '88kg', '彭': '99kg', '凤': '0.68t'}
list1 = []
for i, j in dict1.items():
list1.append([i, j])
print(list1)Conclusion
The article provides a comprehensive overview of converting Python lists to dictionaries, sorting the resulting mapping by weight, and handling various extensions such as nested lists and reverse conversion, with multiple code snippets to help readers solve the problem.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
