blog.finxter.com
Open in
urlscan Pro
194.1.147.89
Public Scan
URL:
https://blog.finxter.com/how-to-get-first-key-value-in-a-dictionary/
Submission: On October 10 via api from US — Scanned from DE
Submission: On October 10 via api from US — Scanned from DE
Form analysis
2 forms found in the DOMPOST https://sendy.finxter.com/subscribe
<form method="post" action="https://sendy.finxter.com/subscribe" id="" autocomplete="new-password" novalidate="novalidate"><input type="hidden" class="tve-f-a-hidden" value="https://sendy.finxter.com/subscribe"><input id="list" type="hidden"
name="list" value="BrvQ8FCGVy9U9L7U48INAg"><input id="subform" type="hidden" name="subform" value="yes">
<div class="tve_lead_generated_inputs_container">
<div class="tve_lg_input_container tve_lg_input tve_lg_regular_input tcb-icon-display" data-selector="#lg-lizqqjg9 .tve_lg_regular_input:not(.tcb-excluded-from-group-item)" data-css="tve-u-188c866835f" data-label="tve-lg-188c87c0b02" style="">
<div class="thrv_wrapper thrv_icon" style=""><svg class="tcb-icon" viewBox="0 0 24 24" data-id="icon-email-check-solid" data-name="">
<path d="M21,13.34C20.37,13.12 19.7,13 19,13A6,6 0 0,0 13,19C13,19.34 13.03,19.67 13.08,20H3A2,2 0 0,1 1,18V6C1,4.89 1.89,4 3,4H19A2,2 0 0,1 21,6V13.34M23.5,17L18.5,22L15,18.5L16.5,17L18.5,19L22,15.5L23.5,17M3,6V8L11,13L19,8V6L11,11L3,6Z">
</path>
</svg></div><input name="email" id="email" type="email" placeholder="Email" value="" data-required="1" data-validation="email" style="" data-placeholder="Email">
</div>
<div class="tve_lg_input_container tcb-plain-text tve-new-checkbox tve_lg_checkbox" data-columns="4" data-selector="#lg-lizqqjg9 .tve_lg_checkbox:not(.tcb-excluded-from-group-item)">
<div class="tve-checkbox-grid">
<div class="tve_lg_checkbox_wrapper tve-updated-dom tcb-local-vars-root" data-value="default" data-selector="#lg-lizqqjg9 .tve_lg_checkbox:not(.tcb-excluded-from-group-item) .tve_lg_checkbox_wrapper:not(.tcb-excluded-from-group-item)"
data-css="tve-u-188c867b5db" style="">
<div class="thrive-colors-palette-config" style="display: none !important"></div>
<input type="checkbox" name="gdpr" data-label-value="1" value="I consent to personalized information and emails: Privacy Policy" id="tve-lg-checkbox-188c87c0b03" data-placeholder="gdpr" placeholder="gdpr">
<label for="tve-lg-checkbox-188c87c0b03">
<span class="tve-checkmark">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<path
d="M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z">
</path>
</svg>
</span>
<span class="tve-input-option-text tcb-plain-text">I consent to personalized information and emails: <a href="https://blog.finxter.com/privacy-policy/" target="_blank" class="" style="outline: none;">Privacy Policy</a></span>
</label>
</div>
</div>
</div>
<div class="thrv_wrapper tve-form-button tcb-local-vars-root tve-color-set" data-selector="#lg-lizqqjg9 .tve-form-button" data-tcb_hover_state_parent="" style="" data-button-size-d="m">
<div class="thrive-colors-palette-config" style="display: none !important"></div>
<a href="#" class="tcb-button-link tve-form-button-submit" style=""><span class="tcb-button-texts" style=""><span class="tcb-button-text thrv-inline-text" style="">Download Free</span><span class="tcb-secondary-text thrv-inline-text" style=""></span></span></a><input
type="submit" style="display: none">
</div>
</div>
<div style="display: none;"></div><input type="hidden" id="tve_mapping" name="tve_mapping" value="YTowOnt9">
</form>
POST https://sendy.finxter.com/subscribe
<form method="post" action="https://sendy.finxter.com/subscribe" id="" autocomplete="new-password" novalidate="novalidate"><input type="hidden" class="tve-f-a-hidden" value="https://sendy.finxter.com/subscribe"><input id="list" type="hidden"
name="list" value="BrvQ8FCGVy9U9L7U48INAg"><input id="subform" type="hidden" name="subform" value="yes">
<div class="tve_lead_generated_inputs_container">
<div class="tve_lg_input_container tve_lg_input tve_lg_regular_input tcb-icon-display" data-selector="#lg-lizqnh3v .tve_lg_regular_input:not(.tcb-excluded-from-group-item)" data-css="tve-u-188c866835f" data-label="tve-lg-188c879dc63" style="">
<div class="thrv_wrapper thrv_icon" style=""><svg class="tcb-icon" viewBox="0 0 24 24" data-id="icon-email-check-solid" data-name="">
<path d="M21,13.34C20.37,13.12 19.7,13 19,13A6,6 0 0,0 13,19C13,19.34 13.03,19.67 13.08,20H3A2,2 0 0,1 1,18V6C1,4.89 1.89,4 3,4H19A2,2 0 0,1 21,6V13.34M23.5,17L18.5,22L15,18.5L16.5,17L18.5,19L22,15.5L23.5,17M3,6V8L11,13L19,8V6L11,11L3,6Z">
</path>
</svg></div><input name="email" id="email" type="email" placeholder="Email" value="" data-required="1" data-validation="email" style="" data-placeholder="Email">
</div>
<div class="tve_lg_input_container tcb-plain-text tve-new-checkbox tve_lg_checkbox" data-columns="4" data-selector="#lg-lizqnh3v .tve_lg_checkbox:not(.tcb-excluded-from-group-item)">
<div class="tve-checkbox-grid">
<div class="tve_lg_checkbox_wrapper tve-updated-dom tcb-local-vars-root" data-value="default" data-selector="#lg-lizqnh3v .tve_lg_checkbox:not(.tcb-excluded-from-group-item) .tve_lg_checkbox_wrapper:not(.tcb-excluded-from-group-item)"
data-css="tve-u-188c867b5db" style="">
<div class="thrive-colors-palette-config" style="display: none !important"></div>
<input type="checkbox" name="gdpr" data-label-value="1" value="I consent to personalized information and emails: Privacy Policy" id="tve-lg-checkbox-188c879dc64" data-placeholder="gdpr" placeholder="gdpr">
<label for="tve-lg-checkbox-188c879dc64">
<span class="tve-checkmark">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<path
d="M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z">
</path>
</svg>
</span>
<span class="tve-input-option-text tcb-plain-text">I consent to personalized information and emails: <a href="https://blog.finxter.com/privacy-policy/" target="_blank" class="" style="outline: none;">Privacy Policy</a></span>
</label>
</div>
</div>
</div>
<div class="thrv_wrapper tve-form-button tcb-local-vars-root tve-color-set" data-selector="#lg-lizqnh3v .tve-form-button" data-tcb_hover_state_parent="" style="" data-button-size-d="m">
<div class="thrive-colors-palette-config" style="display: none !important"></div>
<a href="#" class="tcb-button-link tve-form-button-submit" style=""><span class="tcb-button-texts" style=""><span class="tcb-button-text thrv-inline-text" style="">Download Free</span><span class="tcb-secondary-text thrv-inline-text" style=""></span></span></a><input
type="submit" style="display: none">
</div>
</div>
<div style="display: none;"></div><input type="hidden" id="tve_mapping" name="tve_mapping" value="YTowOnt9">
</form>
Text Content
Skip to content Menu * Finxter Exponential Academy * Prompt Engineer Learning Path (10 Steps) * Books * Puzzles * User Stories * What Our Users Say * About Finxter * Finxter Feedback from ~1000 Python Developers * Video Reviews * Course Review from Cristian * Course Review from Adam * About Chris * Start Here HOW TO GET FIRST KEY VALUE IN A DICTIONARY July 28, 2022July 27, 2022 by Kat McKelvie 3.3/5 - (10 votes) PROBLEM FORMULATION AND SOLUTION OVERVIEW In this article, you’ll learn how to get the first Key and Value from a key:value pair in a Python Dictionary. A Dictionary in Python is used to store information in a key:value pair format. These pairs are modifiable and do not allow duplicates. Note: In theory, the dictionary data type doesn’t provide any guarantee of ordering. In other words, there should be no such thing as getting the “first value” of a dictionary. If your application relies on the ordering of dictionary elements, I’d recommend using the OrderedDict type. In practice, however, things are different because dictionaries, in fact, keep the elements ordered in the cPython implementation of the Python specification. You cannot rely on it, though. To make it more fun, we have the following running scenario: Download your Python cheat sheet, print it out, and post it to your office wall! I consent to personalized information and emails: Privacy Policy Download Free Noah has decided to take his family on a fun getaway. He has a list of five (5) possible choices. After much ado, a vote was taken, and the first location was selected as the winner. Where is the family going (Key)? What are they staying in (Value)? -------------------------------------------------------------------------------- Question: How would we write code to get the first key:value pair in a Python Dictionary? We can accomplish this task by one of the following options: * Method 1: Use dict.items() * Method 2: Use dict.keys() and dict.values() * Method 3: Use next() * Method 4: Use a for loop and dict.items() * Method 5: Use Dictionary Comprehension -------------------------------------------------------------------------------- METHOD 1: USE DICT.ITEMS() This method uses dict.items() to access and retrieve the first key:value pair in a Dictionary. Plain text Copy to clipboard Open code in new window EnlighterJS 3 Syntax Highlighter getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} winner = list(getaways.items()) print(winner) getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} winner = list(getaways.items()) print(winner) getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} winner = list(getaways.items()) print(winner) Above, declares four (4) possible getaways, with the Dictionary Key indicating the location and the Value indicating the accommodations. These save to getaways. The following line converts getaways (list(getaways.items()) to a List and returns a List of Tuples as shown below. [('Switzerland', 'Windmill'), ('Canada', 'Igloo'), ('Sweden', 'Treehouse'), ('US', 'Lighthouse')] To access the first key:value pair, slicing was used to access the Tuple. Plain text Copy to clipboard Open code in new window EnlighterJS 3 Syntax Highlighter winner = list(getaways.items())[0] print(winner) winner = list(getaways.items())[0] print(winner) winner = list(getaways.items())[0] print(winner) ('Switzerland', 'Windmill') To access the Key and Value individually, slicing was used once again. Plain text Copy to clipboard Open code in new window EnlighterJS 3 Syntax Highlighter winner = list(getaways.items())[0][0] print(winner) winner = list(getaways.items())[0][1] print(winner) winner = list(getaways.items())[0][0] print(winner) winner = list(getaways.items())[0][1] print(winner) winner = list(getaways.items())[0][0] print(winner) winner = list(getaways.items())[0][1] print(winner) Switzerland Windmill Python dict.items() Method Watch this video on YouTube -------------------------------------------------------------------------------- METHOD 2: USE DICT.KEYS() AND DICT.VALUES() This method uses dict.keys() and dict.values() to access and retrieve the first key:value pair in a Dictionary. Plain text Copy to clipboard Open code in new window EnlighterJS 3 Syntax Highlighter getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} first_key = list(getaways.keys())[0] first_val = list(getaways.values())[0] print(f'Noah and his family are going to {first_key} and staying in a {first_val}.') getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} first_key = list(getaways.keys())[0] first_val = list(getaways.values())[0] print(f'Noah and his family are going to {first_key} and staying in a {first_val}.') getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} first_key = list(getaways.keys())[0] first_val = list(getaways.values())[0] print(f'Noah and his family are going to {first_key} and staying in a {first_val}.') Above, declares four (4) possible getaways, with the Dictionary Key indicating the location and the Value indicating the accommodations. These save to getaways. The following two (2) lines access the first Key and the first Value using slicing. These save respectively to first_key and first_val. Next, a formatted string is output to the terminal. Noah and his family are going to Switzerland and staying in a Windmill. Python dict.keys() Method Watch this video on YouTube -------------------------------------------------------------------------------- METHOD 3: USE NEXT() For this method, only the Value of the first key:value pair, is retrieved. Plain text Copy to clipboard Open code in new window EnlighterJS 3 Syntax Highlighter getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} all_vals = getaways.values() val_iter = iter(all_vals) first_val = next(val_iter) print(f'Noah and his family are staying in a {first_val}. The location is a secret!') getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} all_vals = getaways.values() val_iter = iter(all_vals) first_val = next(val_iter) print(f'Noah and his family are staying in a {first_val}. The location is a secret!') getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} all_vals = getaways.values() val_iter = iter(all_vals) first_val = next(val_iter) print(f'Noah and his family are staying in a {first_val}. The location is a secret!') Above, declares four (4) possible getaways, with the Dictionary Key indicating the location and the Value indicating the accommodations. These save to getaways. The following three (3) lines retrieve all the Dictionary Values, convert them to an object, retrieve the first Value and output a formatted string to the terminal. Noah and his family are staying in a Windmill. The location is a secret! Python Dictionary values() Method Watch this video on YouTube -------------------------------------------------------------------------------- METHOD 3: USE A FOR LOOP AND DICT.ITEMS() This method uses a for Loop and dict.items() to output the first key:value pair in a Dictionary. Plain text Copy to clipboard Open code in new window EnlighterJS 3 Syntax Highlighter getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} for k, v in getaways.items(): print(k, v) exit() getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} for k, v in getaways.items(): print(k, v) exit() getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} for k, v in getaways.items(): print(k, v) exit() Above, declares four (4) possible getaways, with the Dictionary Key indicating the location and the Value indicating the accommodations. These save to getaways. The next line instantiates a For loop to iterate through the Dictionary items. Then, the first Key and Value are output to the terminal, and the loop terminates. Switzerland Windmill -------------------------------------------------------------------------------- METHOD 5: USE DICTIONARY COMPREHENSION Dictionary Comprehension! A simplistic approach! Plain text Copy to clipboard Open code in new window EnlighterJS 3 Syntax Highlighter getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} winner = {k: getaways[k] for k in list(getaways)[:1]} print(winner) getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} winner = {k: getaways[k] for k in list(getaways)[:1]} print(winner) getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo', 'Sweden': 'Treehouse', 'US': 'Lighthouse'} winner = {k: getaways[k] for k in list(getaways)[:1]} print(winner) Above, declares four (4) possible getaways, with the Dictionary Key indicating the location and the Value indicating the accommodations. These save to getaways. Next, Dictionary Comprehension is used in conjunction with slicing to retrieve only the first Key and Value in the Dictionary and output the same to the terminal. Perfect! {'Switzerland': 'Windmill'} Python Dictionary Comprehension - A Powerful One-Liner Tutorial Watch this video on YouTube A Finxter Favorite! Simple! Yet Elegant! -------------------------------------------------------------------------------- SUMMARY These five (5) methods of retrieving the first Key and Value pair of a Dictionary should give you enough information to select the best one for your coding requirements. Good Luck & Happy Coding! -------------------------------------------------------------------------------- PROGRAMMER HUMOR – BLOCKCHAIN “Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source – xkcd Kat McKelvie At university, I found my love of writing and coding. Both of which I was able to use in my career. During the past 15 years, I have held a number of positions such as: In-house Corporate Technical Writer for various software programs such as Navision and Microsoft CRM Corporate Trainer (staff of 30+) Programming Instructor Implementation Specialist for Navision and Microsoft CRM Senior PHP Coder Categories Data Structures, Python, Python Dictionary Be on the Right Side of Change * The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. * Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world! * Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift. Learning Resources Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development! Join the Finxter Academy and unlock access to premium courses to certify your skills in exponential technologies and programming. New Finxter Tutorials: * 7 Best Ways to Use Newline in an F-String * What Tech Career Would Fit Your Personality Type Based on Myers-Briggs’ 16 Personalities? (Online Tool) * What’s the Default Google Colab Directory To Store Files? * Get First N Google Search Results in Python (Official Way) * 5 Easy Ways to Edit a Text File From Terminal (Linux) – Quick & Efficient Methods * Check Python Version: A Simple Illustrated Guide * 11 Profitable Ways to Make Money as a Prompt Engineer (2023) * pip install unroll Error Code 1: python setup.py egg_info Fixed * What is setup.py? * Regex to Extract All Email Addresses from a String (Tutorial + Online Tool) Finxter Categories: Categories Select Category 2-min Computer Science Concepts 2-min Computer Science Papers Alexa Skills Algorithms Anthropic App Development Arduino Artificial Intelligence async AutoGPT Automation AWS Baby AGI BeautifulSoup Binary Bitcoin Bitcoin Lightning Blogging Books Brownie C C# C++ Career ChatGPT Cheat Sheets Clojure Cloud Computing Coding Business Coding Interview Computer Science Crypto CSS CSV Daily Data Science Puzzle Daily Python Puzzle dApp Dash Data Conversion Data Science Data Structures Data Visualization Database Deep Learning DeFi Dependency Management DevOps Distributed Systems Django Dunder Methods Economy Error Ethereum Excel Exception Handling File Handling Finance Finxter Testimonials Flask Float Freelancing Functional Programming Functions Games Git GitHub Copilot Go Google Bard Graph Theory GUI Hardware Health HTML Image Processing Input/Output Investment Java JavaScript json Julia Jupyter Keras Langchain Large Language Model (LLM) Linux Machine Learning macOS Math Matplotlib Midjourney Natural Language Processing Networking News Newspaper3k NFT Object Orientation Open Source OpenAI OpenCV Operating System Pandas Library Parallel Programming Peer to Peer Systems PeerBrain Performance Philosophy PHP Pillow pip Polygon Powershell Productivity Programming Projects Prompt Engineering PyCharm PyTest Python Python Built-in Functions Python Dictionary Python Email Course Python Keywords Python List Python One-Liners Python Operators Python Requests Python Set Python String Python sys Python Time Python Tuple PyTorch React Regex Research Robotics Scikit-learn Library SciPy Scripting Seaborn Security Selenium shutil sklearn Smart Contracts Solana Solidity Spreadsheet SQL Statistics Streamlit SymPy Tableau Technology TensorFlow Tesla Testing Text Processing The Numpy Library TKinter Tool Trading TryHackMe Ubuntu Visual Studio Web 3 Web Development Web Scraping Windows Wordpress XML * About * Impressum * Privacy * Terms * Earnings Disclaimer * Puzzles * Academy * Books & Courses * Finxter Instagram * Finxter Twitter * Finxter Facebook * Finxter YouTube * Email Newsletter Sponsorship * Finxter Exponential Academy * Prompt Engineer Learning Path (10 Steps) * Books * Puzzles * User Stories * What Our Users Say * About Finxter * Finxter Feedback from ~1000 Python Developers * Video Reviews * Course Review from Cristian * Course Review from Adam * About Chris * Start Here © Finxter 2023 | Instagram | Twitter | Facebook | YouTube PYTHON CHEAT SHEET Join 151,639 tech enthusiasts learning with Finxter I consent to personalized information and emails: Privacy Policy Download Free Ask FinxterGPT (GPT-4) FinxterGPT-4: Hi tech enthusiast! How can I help you? Send By using Chef-GPT, you agree with our privacy policy Finxter Data and Cookie Consent In order to provide a more personal user experience, we and our partners use technology such as cookies to store and/or access device information. By clicking “Accept” you consent to these technologies which will allow us and our partners to process non-sensitive data such as IP address, unique ID, and browsing data for the purposes of serving personalized ads and content, ad and content measurement, audience insights, and to develop and improve products. Your choices on this site will be applied only for this site. You can change your settings at any time, including withdrawing your consent, by going to the Privacy Policy page of this site. Manage Settings Accept Update Privacy Settings