Answers for "how to access dictionary variable in python"

1

get all keys and values from dictionary python

#python 3
for k,v in dict.items():
    print(k, v)
Posted by: Guest on July-31-2020
2

how to get element from dictionary python

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
Posted by: Guest on August-10-2020
1

python dictionary access value by key

# Create a list of dictionary
datadict = [{'Name': 'John', 'Age': 38, 'City': 'Boston'},
 {'Name': 'Sara', 'Age': 47, 'City': 'Charlotte'},
 {'Name': 'Peter', 'Age': 63, 'City': 'London'},
 {'Name': 'Cecilia', 'Age': 28, 'City': 'Memphis'}]

# Build a function to access to list of dictionary
def getDictVal(listofdic, name, retrieve):
    for item in listofdic:
        if item.get('Name')==name:
            return item.get(retrieve)
          
 # Use the 'getDictVal' to read the data item
getDictVal(datadict, 'Sara', 'City') # Return 'Charlotte'

# -------------------
# to convert a dataframe to data dictionary
df = pd.DataFrame({'Name': ['John', 'Sara','Peter','Cecilia'],
                   'Age': [38, 47,63,28],
                  'City':['Boston', 'Charlotte','London','Memphis']})

datadict = df.to_dict('records')
Posted by: Guest on October-22-2020
0

accessing values in dictionary python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print(dict['Name']) # Zara
print(dict['Age']) # 7
Posted by: Guest on June-03-2021
0

python how to get variable value in dict

{'1': 3, '2': 7, '3', 14}
Posted by: Guest on September-08-2020

Code answers related to "how to access dictionary variable in python"

Python Answers by Framework

Browse Popular Code Answers by Language