Sorting a #Python dict by value? Instead of: sorted(d.items(), key=lambda t: t[1]) Use itemgetter. It's cleaner AND ~25% faster: from operator import itemgetter sorted(d.items(), key=itemgetter(1)) Sort by value, then by key: sorted(d.items(), key=itemgetter(1, 0)) # value,key
Sort Python dict by value with itemgetter
More Relevant Posts
-
🐍 #python tips: (range(len(...))) If you’re looping over indexes just to access values, Python has a better, cleaner option: enumerate(). Why it’s better: ✔️ More readable ✔️ Fewer off-by-one bugs ✔️ Idiomatic Python ✔️ Small changes like this compound into more maintainable code What’s interesting is that modern code generators and AI assistants already prefer patterns like enumerate() because they encode intent, not just mechanics. The clearer your code, the better both humans and tools can reason about it. Clean code isn’t about clever tricks! It’s about making the next reader (or code generator) faster and safer. What do you think? #Python #ProgrammingTips #CleanCode #SoftwareEngineering #DeveloperExperience #CodeQuality
To view or add a comment, sign in
-
-
Day 3 Update: Deep Dive into Python String Methods Today, I focused on Python string manipulation and learned the usage of all major built-in string methods, which are essential for text processing and real-world applications. 📌What I learned: Case handling (upper(), lower(), capitalize(), title(), swapcase()) String validation methods (isalpha(), isdigit(), isalnum(), isspace(), isnumeric(), etc.) Searching and indexing (find(), index(), rfind(), startswith(), endswith()) Formatting and alignment (format(), center(), ljust(), rjust(), zfill()) Splitting and joining strings (split(), rsplit(), splitlines(), join()) Trimming and replacing text (strip(), lstrip(), rstrip(), replace()) Encoding and translation concepts (encode(), translate(), maketrans() Understanding these string methods is helping me write cleaner, more efficient Python code and strengthening my foundation for future projects in cloud engineering and automation. Consistent learning, one concept at a time #Python #SoftwareEngineer #LearningJourney #Programming #CloudEngineering #PythonBasics #W3Schools #Consistency
To view or add a comment, sign in
-
-
🚀 Dictionaries: Key-Value Pairs (Python) Dictionaries are unordered collections of key-value pairs. They are defined using curly braces `{}`. Keys must be unique and immutable (e.g., strings, numbers, or tuples), while values can be of any data type. Dictionaries are highly efficient for looking up values based on their keys. They are widely used for representing structured data and implementing mappings. Learn more on our app: https://lnkd.in/gefySfsc #Python #PythonDev #DataScience #WebDev #professional #career #development
To view or add a comment, sign in
-
-
🚀 Day-38 of #100DaysOfCode 🐍 Python Sorting Algorithm Challenge Today I implemented Selection Sort from scratch to sort a list of numbers provided by the user—without using any built-in sorting methods. 🔹 What is Selection Sort? Selection Sort repeatedly selects the smallest element from the unsorted portion of the list and places it at the correct position. 🔹 Concepts Practiced: ✔ Nested loops ✔ Minimum element selection logic ✔ Index tracking ✔ In-place swapping 🔹 Approach: Iterate through the list Find the minimum element in the remaining unsorted part Swap it with the current index Repeat until the list is fully sorted 🔹 Key Insight: Selection Sort has a time complexity of O(n²), making it useful for understanding sorting fundamentals rather than large datasets. Working through such algorithms builds strong foundational knowledge of sorting and array manipulation 💡 #Python #SelectionSort #SortingAlgorithms #CorePython #100DaysOfCode #Day38 #LearnPython #CodingPractice #PythonDeveloper
To view or add a comment, sign in
-
-
How much memory does a text column in your #Python #Pandas data frame use? Check: df['x'].memory_usage() But this is likely a huge underestimate! It sums the pointer sizes, not the string sizes. Instead, say: df['x'].memory_usage(deep=True) Or: df.info(memory_usage='deep')
To view or add a comment, sign in
-
-
Some fun with Python iterators. Let's take some list >>> lst = [1, 2, 3, 4] and build an iterator out of it >>> lst_i = iter(lst) Now I have an iterator over lst, so it should produce elements 1, 2, 3, 4. And indeed, the first element is 1. >>> list(zip(lst_i, ['a'])) [(1, 'a')] But let's see what is left... >>> list(zip(lst_i, ['b', 'c', 'd'])) [(3, 'b'), (4, 'c')] Where did 2 go? Well, the explanation is as following. The first zip gets 1 from lst_i and 'a' from ['a']. Then it gets 2 from lst_i and nothing from ['a'], so 2 is **discarded**. What is left for the second zip is 3 and 4. #Python #gotcha
To view or add a comment, sign in
-
Just published a short article on: 🧠 Objects, Identity, and Mutability in Python If you’ve ever been confused by is vs ==, lists changing unexpectedly, or how Python passes arguments to functions this is for you. 🔗⬇️ https://lnkd.in/dTBQAzjW
To view or add a comment, sign in
-
Strings are everywhere in Python, and mastering string methods makes your code cleaner, faster, and more efficient. This visual covers commonly used Python string methods like: Case conversion (upper(), lower(), title()) Searching & counting (find(), index(), count()) Validation checks (isdigit(), isalpha(), islower()) Formatting & alignment (format(), center(), ljust(), rjust()) Cleaning & splitting (strip(), replace(), split()) These methods are extremely useful in Data Analytics, Data Cleaning, and Text Processing. #Python #DataAnalytics #PythonProgramming #LearningPython #DataScience #Coding #Developer #Analytics
To view or add a comment, sign in
-
-
🐍 Did you know Python has a built-in lru_cache decorator that can make your functions much faster? It works by remembering the results of expensive function calls. So when the same input is used again, Python returns the cached result instead of recalculating it. Example: Fibonacci with caching: ━━━━━━━━━━━━━━━━━━━━ from functools import lru_cache @lru_cache() def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) ━━━━━━━━━━━━━━━━━━━━ ⏱ Without lru_cache: Calculating fib(35) takes over 2.36 seconds ⏱ With lru_cache: Calculating fib(35) takes just 0.00002 seconds! Check out the video I made to see this speed difference in action #Python #SoftwareEngineering #BackendDevelopment #ProgrammingTips #PerformanceOptimization
To view or add a comment, sign in
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development