Skip to content
Fix Code Error

How to print a dictionary’s key?

March 13, 2021 by Code Error
Posted By: Anonymous

I would like to print a specific Python dictionary key:

mydic = {}
mydic['key_name'] = 'value_name'

Now I can check if mydic.has_key('key_name'), but what I would like to do is print the name of the key 'key_name'. Of course I could use mydic.items(), but I don’t want all the keys listed, merely one specific key. For instance I’d expect something like this (in pseudo-code):

print "the key name is", mydic['key_name'].name_the_key(), "and its value is", mydic['key_name']

Is there any name_the_key() method to print a key name?


Edit:
OK, thanks a lot guys for your reactions! 🙂 I realise my question is not well formulated and trivial. I just got confused because i realised key_name and mydic['key_name'] are two different things and i thought it would incorrect to print the key_name out of the dictionary context. But indeed i can simply use the ‘key_name’ to refer to the key! 🙂

Solution

A dictionary has, by definition, an arbitrary number of keys. There is no “the key”. You have the keys() method, which gives you a python list of all the keys, and you have the iteritems() method, which returns key-value pairs, so

for key, value in mydic.iteritems() :
    print key, value

Python 3 version:

for key, value in mydic.items() :
    print (key, value)

So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.

Answered By: Anonymous

Related Articles

  • Can't install via pip because of egg_info error
  • How do I merge two dictionaries in a single…
  • Dynamically Adding paper-dropdown-input inside a…
  • What's the difference between KeyDown and KeyPress in .NET?
  • How can I pass a wct test while rearranging children…
  • How to generate a random number in C++?
  • What's the difference between eval, exec, and compile?
  • Pandas - Reshape a dataframe columns based on…
  • What are the currently supported CSS selectors…
  • How to update Python?
  • In CSS Flexbox, why are there no "justify-items" and…
  • How to write :hover condition for a:before and a:after?
  • Database development mistakes made by application developers
  • Is it possible to apply CSS to half of a character?
  • Deleting Row in SQLite in Android
  • Are dictionaries ordered in Python 3.6+?
  • Install pip in docker
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Making a map of composite types typescript
  • Usage of __slots__?
  • Reaction Listener in discord.py
  • Smart way to truncate long strings
  • I'm trying to use a stored procedure or function…
  • How to test if parameters exist in rails
  • VueJs single file component not reading data/props/methods
  • Is there a way to manually handle exception from…
  • Python is not calling fucntions properly
  • What is a NullReferenceException, and how do I fix it?
  • Discord.js: how can I make paticular permissons for…
  • Argument Exception "Item with Same Key has already…
  • Using normal python variables and writing them into…
  • Fix top buttons on scroll of list below
  • How to filter a RecyclerView with a SearchView
  • CSS selector for first element with class
  • How to remove key and all its values in a nested…
  • Approval/Denial System using Discord.js
  • Relative imports for the billionth time
  • JavaScript hashmap equivalent
  • discord.js: How do I replace reactions with buttons…
  • Convert Django Model object to dict with all of the…
  • What are type hints in Python 3.5?
  • Start redis-server with config file
  • Polymer 1.0: Sorting iron-list
  • Are nested try/except blocks in Python a good…
  • What does Ruby have that Python doesn't, and vice versa?
  • How can I access and process nested objects, arrays or JSON?
  • Dictionary returning a default value if the key does…
  • Remove similar tuple from dictionary of tuples
  • Last Key in Python Dictionary
  • Keras Sequential API is replacing every layer with…
  • Remove multiple keys and values with its nested…
  • Reference - What does this regex mean?
  • Angular/Typescript @Output with Union return types
  • Should I use 'has_key()' or 'in' on Python dicts?
  • How to test a global event bus in VueJS
  • Add Keypair to existing EC2 instance
  • Python Dictionary Comprehension
  • Case insensitive access for generic dictionary
  • React: how to update state.item[1] in state using setState?
  • Max function using divide and conquer approach is…
  • What version of Python is on my Mac?
  • Deleting an element from an array in PHP
  • Polymer data-binding: how to access data in nested template?
  • Linking of Page on same page with nextjs
  • Change a HTML5 input's placeholder color with CSS
  • How not to get a repeated attribute of an object?
  • Manually raising (throwing) an exception in Python
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Using Event Aggregator to load a view with different…
  • How to move back and forth for help page using…
  • When should iteritems() be used instead of items()?
  • Install opencv for Python 3.3
  • What's the best way to get the last element of an…
  • Why is "except: pass" a bad programming practice?
  • data.table vs dplyr: can one do something well the…
  • Polymer 1.x: Observers
  • Android ListView not refreshing after notifyDataSetChanged
  • Up, Down, Left and Right arrow keys do not trigger…
  • Polymer 1.x: Pre-load element attributes
  • Google Sheets Script Array Length Returning Null
  • How to create a function which converts an array…
  • How can I remove an SSH key?
  • How can I install a previous version of Python 3 in…
  • How to delete items from a dictionary while…
  • how can i get the id of an emoji in reaction?
  • Observe property on an array of objects for any changes
  • Iron-data-table fails to populate data from databinding
  • Python Variable Declaration
  • Centering in CSS Grid
  • Black transparent overlay on image hover with only CSS?
  • Iterating Over Dictionary Key Values Corresponding…
  • How to specify line breaks in a multi-line flexbox layout?
  • Bad state: field does not exist within the…
  • Copy data from one existing row to another existing…
  • Animation of each element separately in the v -for…
  • LINQ select in C# dictionary
  • How to evaluate an expression in polymer (equivalent…
  • The definitive guide to form-based website authentication
  • How to remove all ListBox items?
  • Change the name of a key in dictionary

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Global variables in Java

Next Post:

Sorting object property by values

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error