Introduction
Python dictionary data structure is like a map in another language like java or associative array in php. It's use a name value pairs.
How To
You use bracket for declaring and defining it. Here's a code.
Program Code
data = {"name":"lady gaga", "city":"new york", "age":24}
print data
print data
Output
{"name":"lady gaga", "city":"new york", "age":24}
Accessing And Modifying Element
For accessing a value, you use its name. For example, you want to access name value, so you use its name key.
Program Code
data = {"name":"lady gaga", "city":"new york", "age":24}
print "Name: ", data["name"] print "City: ", data["city"]
print "Age: ", data["age"]
print "Name: ", data["name"] print "City: ", data["city"]
print "Age: ", data["age"]
Output
Name: lady gaga
City: new york
Age: 24
City: new york
Age: 24
Program Code
data = {"name":"lady gaga", "city":"new york", "age":24}
data["name"] = "jenifer lopez"
print data
data["name"] = "jenifer lopez"
print data
Output
{"city":"new york", "name":"jenifer lopez", "age":24}
Iterating Elements
Here's a code that just iterate for the keys
Program Code
data = {"name":"lady gaga", "city":"new york", "age":24}
for item in data:
print item
Output
city
age
name
age
name
Program Code
data = {"name":"lady gaga", "city":"new york", "age":24}
for key in data:
print data[key]
for key in data:
print data[key]
Output
new york
lady gaga
24
lady gaga
24
No comments:
Post a Comment