|
| 1 | +# python中的列表对应Java中的数组,字典对应的是集合(Map) |
| 2 | +# 是结构相同的组成的一个整体 |
| 3 | +# 获取--R |
| 4 | +alien_0 = {'color': 'Green', 'point': 5} |
| 5 | +print(alien_0['color']) |
| 6 | +print(alien_0['point']) |
| 7 | + |
| 8 | +# 添加--C |
| 9 | +alien_0['x_position'] = 100 |
| 10 | +alien_0['y_position'] = 200 |
| 11 | +print(alien_0) |
| 12 | + |
| 13 | +# 修改--U |
| 14 | +alien_0['color'] = 'Red' |
| 15 | +print(alien_0) |
| 16 | + |
| 17 | +# 删除--D |
| 18 | +del alien_0['y_position'] |
| 19 | +print(alien_0) |
| 20 | + |
| 21 | +# 遍历字典 |
| 22 | +students = {'Tom': 'Java', 'Lily': 'C++', 'John': 'Kotlin', 'Jack': 'Swift'} |
| 23 | +for name, language in students.items(): |
| 24 | + print(name + ' like ' + language) |
| 25 | + |
| 26 | +# 只获取key或者value |
| 27 | +print('只获取key') |
| 28 | +for name in students.keys(): |
| 29 | + print(name) |
| 30 | + |
| 31 | +print('只获取value') |
| 32 | +for language in students.values(): |
| 33 | + print(language) |
| 34 | + |
| 35 | +# 类似的,内部是无序的,现在要求按特定的顺序返回 |
| 36 | +print('按字母顺序返回key或者value') |
| 37 | +for name in sorted(students.values()): |
| 38 | + print(name) |
| 39 | + |
| 40 | +print('按key的排序返回value') |
| 41 | +for name in sorted(students): |
| 42 | + print(name + ' like ' + students[name]) |
| 43 | + |
| 44 | +# 嵌套 |
| 45 | +worker = {'worker1': 'worker1', 'worker2': 'worker2'} |
| 46 | +farmer = {'farmer1': 'farmer', 'farmer2': 'farmer2'} |
| 47 | +teacher = {'teacher1': 'teacher1', 'teacher2': 'teacher2'} |
| 48 | + |
| 49 | +persons = [worker, farmer, students] |
| 50 | +for person in persons: |
| 51 | + print(person) |
| 52 | + |
| 53 | +# 在字典中存储列表 |
| 54 | +data = {'code': 404, 'result': ['lily', 'tom']} |
| 55 | +for name in data['result']: |
| 56 | + print(name.title()) |
| 57 | + |
| 58 | +favorite_languages = { |
| 59 | + 'jen': ['python', 'ruby'], |
| 60 | + 'sarah': ['c'], |
| 61 | + 'edward': ['ruby', 'go'], |
| 62 | + 'phil': ['python', 'haskell'], |
| 63 | +} |
| 64 | + |
| 65 | +for name, languages in favorite_languages.items(): |
| 66 | + print('\n' + name + "'s favorite languages are:") |
| 67 | + for language in languages: |
| 68 | + print('\t' + language) |
| 69 | + |
| 70 | +# 字典中存储字典 |
| 71 | + |
| 72 | +users = { |
| 73 | + 'aeinstein': { |
| 74 | + 'first': 'albert', |
| 75 | + 'last': 'einstein', |
| 76 | + 'location': 'princeton', |
| 77 | + }, |
| 78 | + 'mcurie': { |
| 79 | + 'first': 'marie', |
| 80 | + 'last': 'curie', |
| 81 | + 'location': 'paris', |
| 82 | + }, |
| 83 | +} |
| 84 | + |
| 85 | +for user_name, user_info in users.items(): |
| 86 | + print('\nUseName:' + user_name + '\r') |
| 87 | + fullName = user_info['first'] + user_info['last'] |
| 88 | + address = user_info['location'] |
| 89 | + print('Full Name:' + fullName.title() + '\r\n' + 'Address:' + address) |
0 commit comments