【python】 dictionary
2345 ワード
いくつかの辞書の基本的な操作.items() .keys() .values() .get(self,key,dafault)sorted()この辞書を並べ替えると、リストが返されます
import operator
#
# a = {...}
#key-value (value )
def base_operate():
alien = {'color': 'yellow', 'points': 5}
print(alien['color'])
print(alien['points'])
#print(alien['3']) # KeyError: '3'
#print(alien[0]) #
# key-value
alien['head'] = "so big"
print(alien['head'])
#
del(alien['points'])
print(alien)
#
# — ,
print(alien.items()) # —
for key, value in alien.items():
print(key + ": " + value)
print(alien.keys()) #
for key in alien.keys():
print(key)
print(len(alien.keys())) # 2
# not in
# if "hand" not in alien.keys():
# alien["hand"] = 2
# print(alien["hand"]) # 2
alien["hand"] = 3
#.get(self, key, default)
alien["hand"] = alien.get("hand", 2)
print(alien["hand"]) # alien["hand"] = 3 , 2, 3
# key
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
# value
for value in favorite_languages.values():
print(value)
# !!!!!!!
nation = {"china": 200, 'usa': 300, "japan": 100}
# key ,
# operator itemgetter , ( )
sortedNation = sorted(nation.items(), key = operator.itemgetter(1))
print(type(sortedNation)) #
print(sortedNation) # key = operator.itemgetter(1) [('japan', 100), ('china', 200), ('usa', 300)]
#print(sortedNation) # key = operator.itemgetter(0) [('china', 200), ('japan', 100), ('usa', 300)]
print(sortedNation[0][0]) # china
def main():
base_operate()
if __name__ == "__main__":
main()