Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

accessing dictionary elements in python

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
x = thisdict["model"]
Comment

Accessing elements from a Python Dictionary

# welcome to softhunt.net
# Python program to demonstrate
# accessing a element from a Dictionary

# Creating a Dictionary
Dictionary = {0: 'Softhunt', 1: '.net', 2: 'By Ranjeet', 'user': 'Greetings to you'}
print("Dictionary", Dictionary)

# accessing a element using key
print("Accessing a element using key:", Dictionary['user'])

# accessing a element using key
print("Accessing a element using key:", Dictionary[2])
Comment

Accessing Elements from Dictionary

# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error
# Output None
print(my_dict.get('address'))

# KeyError
print(my_dict['address'])
Comment

accessing dictionary elements in python


>>> mydict["Apple"]
{'American': '16', 'Mexican': 10, 'Chinese': 5}

Comment

python dictionary accessing an element

IN PYTHON 
unlike javascript don't use . operator to create/assign dic. keys to value
use dic[key] syntax not dic.key(like java script)

NOTE:
in pythyon oops we only use  . operator to access methods and attributes
and to even access using reference variable like head in linkedlist
Comment

PREVIOUS NEXT
Code Example
Python :: python chatbot api 
Python :: what are arrays in python 
Python :: create login user django command 
Python :: last element python 
Python :: how to create a subset of a dataframe in python 
Python :: add dataframe column to set 
Python :: reverse the string in python 
Python :: python replace variable in string 
Python :: how to get a user input in python 
Python :: tri python 
Python :: tkinter bg button 
Python :: opencv python rgb to hsv 
Python :: how to sleep() in python 
Python :: how to add number to string in python 
Python :: user passes test django 
Python :: add item to python list 
Python :: how to reduce the image files size in python 
Python :: odd number sum in python 
Python :: python type checking boolean 
Python :: prettify json in pycharm 
Python :: Dependency on app with no migrations: 
Python :: pytorch get tensor dimension 
Python :: editing specific line in text file in python 
Python :: TypeError: cannot unpack non-iterable float object evaluate 
Python :: python excel sheet import 
Python :: I**2 python 
Python :: wavelet transform in machine learning 
Python :: python while loop and recursion 
Python :: required depend filed odoo 
Python :: derivative of multivariable function pytorch 
ADD CONTENT
Topic
Content
Source link
Name
8+7 =