𝗗𝗮𝘆 𝟭𝟲: 𝗗𝗶𝗰𝘁𝗶𝗼𝗻𝗮𝗿𝘆 𝗶𝗻 𝗣𝘆𝘁𝗵𝗼𝗻 🐍 🔹 A dictionary is a built-in, mutable data structure that stores data in key–value pairs 🔹 Key–value pairs are separated by commas and enclosed in curly braces {} 🔹 Data is stored as key : value 🔹 Keys must be unique 🔹 Dictionaries are ordered (from Python 3.7+) 𝗔𝗰𝗰𝗲𝘀𝘀𝗶𝗻𝗴 𝗗𝗶𝗰𝘁𝗶𝗼𝗻𝗮𝗿𝘆 𝗜𝘁𝗲𝗺𝘀 🔹 Two main ways to access values: 1️⃣Using keys → dict_name[key] (raises error if key not found) 2️⃣Using get() → dict_name.get(key) (returns None if key not found) 🔹 Access all values using → dict_name.values() 𝗔𝗱𝗱𝗶𝗻𝗴 & 𝗠𝗼𝗱𝗶𝗳𝘆𝗶𝗻𝗴 𝗜𝘁𝗲𝗺𝘀 ➕Using assignment operator → dict_name[key] = value ➕ Using update() → adds or updates key-value pairs 𝗥𝗲𝗺𝗼𝘃𝗶𝗻𝗴 𝗜𝘁𝗲𝗺𝘀 ❌ del dict_name[key] → removes a specific key ❌ pop(key) → removes key and returns its value ❌ popitem() → removes the last inserted key-value pair ❌ clear() → removes all items #Python #Dictionary #LearningPython #LearningInPublic #Consistency
Python Dictionary Basics and Methods
More Relevant Posts
-
NumPy Memory Order: Choose C vs F to Match Your Data Access (and Get Faster Code) In Python's NumPy, you can control how an array is stored in contiguous memory using the order setting. There are two order styles: C-style F-style A = [ [1, 2, 3], [4, 5, 6] ] 1) C-order (Row-major): Data is laid out row by row → best when you process one person/record at a time. Syntax: a_c = np.array(a, order="C") Memory: [ 1, 2, 3, 4, 5, 6 ] Walk : (0,0)(0,1)(0,2)(1,0)(1,1)(1,2) 2) F-order (Column-major): data is laid out column by column → best when you process one feature/column for everyone Syntax: a_f = np.array(a, order="F") Memory: [ 1, 4, 2, 5, 3, 6 ] Walk : (0,0)(1,0)(0,1)(1,1)(0,2)(1,2) Row slicing is “cheap” in C-order. Column slicing is “cheap” in F-order. Performance takeaway: -->fewer cache misses. -->faster scans in your hot loop. -->lower memory overhead. -->more stable latency. -->no hidden copies during slicing/transforms/native calls.
To view or add a comment, sign in
-
Day 7 of #200DaysOfCode! 🚀 One week down! Today, I took a break from complex data structures to parse some ancient history: "Roman to Integer" (LeetCode 13). 🏛️ At first glance, this seems like simple addition. You just sum up the symbols, right? III = 1 + 1 + 1 = 3 XV = 10 + 5 = 15 But the "Subtraction Rule" throws a wrench in the works. If a smaller symbol appears before a larger one (like IV or IX), it subtracts instead of adds. The Logic (The Lookahead Technique): Instead of complicated string parsing or multiple passes, I used a clean linear scan with a simple rule: Map the Values: I used a Python Dictionary (Hash Map) to store the values ('I': 1, 'V': 5, etc.) for instant lookups. Iterate & Compare: I looped through the string and simply peeked at the next character. * If Current < Next: It means we are in a subtraction case (like the I in IV). I subtract the current value from the total. Otherwise: I simply add the current value. Example: For MCMXCIV (1994): C (100) < M (1000) → Subtract 100 X (10) < C (100) → Subtract 10 I (1) < V (5) → Subtract 1 This logic handles every edge case in a single pass O(N). The result was a flawless 0 ms runtime, beating 100.00% of Python submissions! 7 days in, and the streak is strong. 🧱 Have you tried the reverse problem (Integer to Roman)? I hear the logic is quite different! 👇 #200DaysOfCode #Python #LeetCode #Algorithms #HashMap #Logic #ProblemSolving #CodingChallenge #DeveloperJourney
To view or add a comment, sign in
-
-
Common #DataTypes in #Python In #DataScience, understanding #DataTypes is the first step to working with data correctly. #Numeric Used for numbers and calculations - #Integer → whole numbers (10, 25, -3) - #Float → decimal values (12.5, 99.8) - #Complex → numbers with real and imaginary parts #Sequence Used for ordered data - #String → text values like names or labels - #List → ordered data that can be changed -#Tuple → ordered data that cannot be changed #Mapping Used to connect keys with values - #Dictionary → stores data in key–value pairs #Set Used to store unique values - #Set → removes duplicates automatically #Boolean Used for conditions and decisions - #Bool → True or False Why #DataTypes Matter - Help in proper #DataCleaning - Improve accuracy in #Analysis - Prevent errors in #MachineLearning workflows Key Takeaway Choosing the right #DataType makes data easier to manage, analyze, and trust. #Python #DataScience #DataTypes #MachineLearning #Analytics #ProgrammingFundamentals #TechCareers #LearningJourney
To view or add a comment, sign in
-
-
Let's talk about Pandas. Pandas helps you turn messy data into clear answers using code. Imagine you have a huge spreadsheet with things like: 🐻❄️ names 🐻❄️scores 🐻❄️dates 🐻❄️locations But it’s messy: >some rows are missing values >some names are repeated >numbers are written in different formats Pandas is a Python library that helps you fix and understand this data. It can: +organize data into clean tables +filter what you want (only top scores, only recent dates) +calculate things (averages, totals, trends) +repeat the same steps automatically on new data #pandas #finance #dataset #python #simple
To view or add a comment, sign in
-
-
Python for loops for data visualization used to trip me up every single time. The syntax made sense in theory, but when it came to putting the right variables in the right order for a complex Seaborn or Matplotlib chart, my brain would just stall. I’m a visual learner. Documentation is great, but sometimes I need to "see" the logic before it clicks. To break through the wall, I went back to basics: markers and paper. 🖍️ I hand-wrote the code for a loop I was building for a recent analytics project. I used different colors to map out exactly where each "piece" was being used and how the data was flowing through the loop. Is the syntax 100% perfect? Probably not. Was it a "waste of time"? For some, maybe. But for me, it was the "Aha!" moment I needed. Now, when I’m stuck, I have this color-coded cheatsheet to ground me. The more I build, the more the official documentation starts to feel like a second language rather than a foreign one. The takeaway: Don't apologize for how you learn. Whether it's hand-drawn diagrams, rubber duck debugging, or color-coded markers—do what helps YOU grow. #DataAnalytics #Python #LearningJourney #DataVisualization
To view or add a comment, sign in
-
-
Data cleaning is the foundation of every analysis. I wanted to share a short paper I recently wrote comparing Python and Excel for common data-cleaning tasks, including: • Clearing extra spaces • Converting text to numbers • Handling duplicates • Managing missing data Key takeaway: it’s not about which tool is “better,” but which tool fits the problem. Would love to hear how others decide between tools in their work.
To view or add a comment, sign in
-
I'm still getting myself adapted to bigger codes in python data cleaning without fearing the error messages knowing that the error message in any data code is a direction to progress not to stay. Renaming columns in Pandas is a breeze! Renaming Columns ✍️Single column: df.rename(columns={'old_name': 'new_name'}) ✍️Multiple columns*: `df.rename(columns={'old1': 'new1', 'old2': 'new2'}) ✍️All columns*: `df.columns = ['new1', 'new2', ...] This is one unique code I like using df.loc[row number, "old name"] = "New name" Tips 📌Use `inplace=True` to modify the original df 📌Be cautious with column name typos! You can reach out to us at HiiT Plc on daily Data Analysis challenge building to join a team of like minded tech guru. #DataAnalysis #DataVisualization #BusinessIntelligence #DataDriven #Analytics #DataStorytelling
To view or add a comment, sign in
-
How Does Strikethrough in Excel Work Written by $DiligentTECH💀⚔️ Does your spreadsheet feel like a graveyard of forgotten promises? Have you ever gazed at a cell and felt the weight of a SyntaxError in your soul, wishing you could just... let go? https://lnkd.in/dy_zauDp In the standard script of life, not every line of code deserves to be executed. Sometimes, we need to keep the memory of a variable alive while ensuring it no longer impacts our final output. 1. The Syntax of Letting Go In Python, we use # to comment out thoughts that no longer serve the logic of our main function. In the study of Excel, Strikethrough is that elegant horizontal line that whispers, "I remember you, but you are no longer my reality." It isn't a del command that erases the data forever; it’s a visual False boolean. https://lnkd.in/daeRnb93
To view or add a comment, sign in
-
-
#python Automated Data Cleaning Manually cleaning these files every week is a soul-crushing waste of time. We need a Python-based Automated Pipeline to standardize data for analysis. The Solution: A Python Validation Script Using the pandas library, we can create a script that acts as a "gatekeeper," cleaning the data automatically and flagging errors that require human intervention. import pandas as pd import numpy as np def clean_sales_data(file_path): # 1. Load data df = pd.read_csv(file_path) # 2. Standardize Column Names (lowercase, no spaces) df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_') # 3. Fix Dates (coerces errors to 'NaT') df['date'] = pd.to_datetime(df['date'], errors='coerce') # 4. Handle Categorical Inconsistency # Maps variations to a single standard mapping = {'nortth': 'North', 'north': 'North', 'sth': 'South', 'south': 'South'} df['region'] = df['region'].str.lower().map(mapping) # 5. Remove Rows with missing critical info (like Revenue) df = df.dropna(subset=['revenue']) return df # Usage # clean_df = clean_sales_data('weekly_report.csv')
To view or add a comment, sign in
Explore related topics
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