Tips python dictionary


                  Dictionary little knowledge
dic = { "name": "tom", "Age": 23, ". Price": 110}
# 01 : extract key
  
print("1>>", dic["name"],type(dic["name"]))  # 1>> tom    <class 'str'>
print("2>>", dic.get("name"))  # 1>> tom
print("3>>", dic.get("n"),type(dic.get("n")))  # 3>> None   <class 'NoneType'>
View Code
# 02: Evaluating key or value exists
  
1 print('name' in dic)   #True
2 print('tom' in dic)   #False
3 print('n' in dic)   #False
View Code
# 03 : Setting the value of the specified field
  
dic['name']="jack"
print(dic)  #{'name': 'jack', 'age': 23, 'price': 110}
print(dic['name'])  # jack
View Code
# 04: access to all the keys and values

 

  
# 1:提取所有的键
print(dic.keys())  # dict_keys(['name', 'age', 'price'])
print(type(dic.keys()))  # <class 'dict_keys'>

# 2:提取所有的值
print(dic.values())  # dict_values(['tom', 23, 110])
print(type(dic.values()))  # <class 'dict_values'>

for key, value in dic.items():
    print(">>", key, value)

>> name tom
>> age 23
>> price 110
View Code
 

 

 

Guess you like

Origin www.cnblogs.com/one-tom/p/10494568.html