Python 数据类型之 dict(讲解+案例+FAQs)

FAQs

1. 一次获取字典多个值

问题描述

无法通过 .get() 方法传入多个键值获得字典多个值

>>> list1 = ['one', 'two', 'three']
>>> list2 = [1, 2, 3]
>>> mydict = dict(zip(list1,list2))
>>> mydict.get('one')
1
>>> mydict.get('one','two')
1
>>> mydict['one']
1
>>> mydict['one','two']
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    mydict['one','two']
KeyError: ('one', 'two')

解决方法1 : from operator import itemgetter

from operator import itemgetter
>>> itemgetter('one','two')(mydict) # 传入键值
(1, 2)
>>> itemgetter(*['one','two'])(mydict)# 传入字典列表,加*
(1, 2)
>>> itemgetter(['one','two'])(mydict) # 传入字典列表,不加*
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    itemgetter(['one','two'])(mydict)
TypeError: unhashable type: 'list'

解决方法2:from pydash import at (该方法需要安装 pydash 模块)

from pydash import at
dict = {'a': 1, 'b': 2, 'c': 3}
list = at(dict, 'a', 'b')
list == [1, 2]

2. 函数返回值为字典

def func1():
    parameters = {'a':1,'b':2,'c':3}
    return parameters
    
func1().get('a')
输出:1

Introduction to Dictionary

Definition:

A dictionary is an unordered set of key: value pairs.

menu = {"oatmeal": 3, "avocado toast": 6, "carrot juice": 5, "blueberry muffin": 2}
  1. A dictionary begins and ends with curly braces ({ and }).
  2. Each item consists of a key (i.e., “oatmeal”) and a value (i.e., 3)
  3. Each key: value pair (i.e., "oatmeal": 3 or "avocado toast": 6) is separated by a comma (,)
  4. It’s considered good practice to insert a space () after each comma, but your code will still run without the space.

Difference between dictionary and list

List: a collection of oredered objetcs

Dictionary: a collection of unordered objects

Benifits:

  • Use a key to get a value from a dictionary
  • Check for existence of keys
  • Find the length of a dictionary
  • Iterate through keys and values in dictionaries
  • Describe related information of an object using a bunch of key-value pair In a complex scenario
  • put many dict in a list, iterating each of elemen for the same operation
card_list = [{"name": "张三",
              "qq": "12345",
              "phone": "110"},
             {"name": "李四",
              "qq": "54321",
              "phone": "10086"}
             ]

Key points:

  • list or dictionary can not be key

    string,number, tuple (immutable)

  • Hash the key to determine how to store the dictionary’s data in memory

    • key : immutable data type
    • value : any type of data

Inspect

dict.keys()
dict.values()
dict.items()

Add a key (overwrite) /multiple keys .update()

# add a key
Dict[key] = value
if key has existed, To modify previous data
Dict.setdefault(key,value)
if key has existed, Keep the original one

animals_in_zoo={}
animals_in_zoo["zebras"] = 8
animals_in_zoo["monkeys"] = 12
animals_in_zoo["dinosaurs"] = 0
animals_in_zoo["dinosaurs"] = 2
print(animals_in_zoo)

# multiple keys
user_ids.update({"theLooper":138475, "stringQueen": 85739})

# overwrite
oscar_winners = {"Best Picture": "La La Land", "Best Actor": "Casey Affleck", "Best Actress": "Emma Stone", "Animated Feature": "Zootopia"}
oscar_winners["Supporting Actress"] = "Viola Davis"
oscar_winners["Best Picture"] = "Moonlight"

Del

del dict[key]
dict.pop(key)  
dict.popitem()    # randomly delete
dict.clear()

List Comprehensions to Dictionaries

names = ['Jenny', 'Alexus', 'Sam', 'Grace']
heights = [61, 70, 67, 64]
students = {key:value for key, value in zip(names, heights)}
#students is now {'Jenny': 61, 'Alexus': 70, 'Sam': 67, 'Grace': 64}

Takes a pair from the zipped list of pairs from names and heights
Names the elements in the pair key (the one originally from the names list) and value (the one originally from the heights list)
Creates a key : value item in the students dictionary
Repeats steps 1-3 for the entire list of pairs
songs = ["Like a Rolling Stone", "Satisfaction", "Imagine", "What's Going On", "Respect", "Good Vibrations"]
playcounts = [78, 29, 44, 21, 89, 5]
plays = {song:playcount for song, playcount in zip(songs,playcounts)}
print(plays)
plays["Purple Haze"] = 1
plays["Respect"] = 94

library = {"The Best Songs": plays, "Sunday Feelings": {}}
print(library)

Using Dictionaries

Key points:

Try/Except to Get a Key

caffeine_level = {"espresso": 64, "chai": 40, "decaf": 0, "drip": 120}

caffeine_level["matcha"] = 30
key_to_check = "matcha"
try:
  print(caffeine_level[ key_to_check])
except KeyError:
  print("Unknown Caffeine Level")

Safely Get a Key for safe input .get()

# specify a value if the key doesn't exist
>>> building_heights.get('Shanghai Tower', 0)
632
>>> building_heights.get('Mt Olympus', 0)
0
>>> building_heights.get('Kilimanjaro', 'No Value')
'No Value'

Delete a key .pop( )

raffle = {223842: "Teddy Bear", 872921: "Concert Tickets", 320291: "Gift Basket", 412123: "Necklace", 298787: "Pasta Maker"}
raffle.pop(320291, "No Prize")
"Gift Basket"
# 存在则返回键值,不存在则返回逗号后值

Get All Keys .keys( )

user_ids = {"teraCoder": 100019, "pythonGuy": 182921, "samTheJavaMaam": 123112, "lyleLoop": 102931, "keysmithKeith": 129384}
num_exercises = {"functions": 10, "syntax": 13, "control flow": 15, "loops": 22, "lists": 19, "classes": 18, "dictionaries": 18}

users = user_ids.keys()
users1 = list(user_ids)
lessons = num_exercises.keys()

print(users)
print(users1)
print(lessons)

dict_keys(['teraCoder', 'pythonGuy', 'samTheJavaMaam', 'lyleLoop', 'keysmithKeith'])
A dict_keys object is a view object, which provides a look at the current state of the dicitonary, without the user being able to modify anything.
['teraCoder', 'pythonGuy', 'samTheJavaMaam', 'lyleLoop', 'keysmithKeith']

dict_keys(['functions', 'syntax', 'control flow', 'loops', 'lists', 'classes', 'dictionaries'])

Get all values

num_exercises = {"functions": 10, "syntax": 13, "control flow": 15, "loops": 22, "lists": 19, "classes": 18, "dictionaries": 18}
total_exercises = 0
for num in num_exercises.values():
  total_exercises += num
print (total_exercises)

Get All Items

pct_women_in_occupation = {"CEO": 28, "Engineering Manager": 9, "Pharmacist": 58, "Physician": 40, "Lawyer": 37, "Aerospace Engineer": 9}
for occupation, value in pct_women_in_occupation.items():
  print("Women make up " +str(value) +" percent of "+occupation+ "s.")

Project 01 — Scrabble

letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]

letter_to_points = {letter: point for letter, point in zip(letters, points)}
letter_to_points[" "]=0

def score_word(word):
  point_total = 0
  for letter in word:
    point_total += letter_to_points.get(letter,0)
  return point_total

brownie_points = score_word("BROWNIE")
#print(brownie_points)
player_to_words = {"wordNerd": "EARTH EYES MACHINE", "Lexi Con": "ERASER BELLY HUSKY" , "Prof Reader": "ZAP	COMA PERIOD"}
player_to_points = {}

for item in player_to_words:
  player_points = 0
  for word in player_to_words[item]:
    player_points += score_word(word)
  player_to_points[item] = player_points
print(player_to_points)

Project 02— unique Values

oscars = {"Best Picture": "Moonlight", "Best Actor": "Casey Affleck", "Best Actress": "Emma Stone", "Animated Feature": "Zootopia"}

for element in oscars:
  print(element)

# Unique Values
def unique_values (my_dictionary):
  num_value = 0
  before_letter = []
  for value in my_dictionary.values():
    if not value in  before_letter:
      num_value += 1
    before_letter.append(value)
  return num_value
# Uncomment these function calls to test your  function:
# print(unique_values({0:3, 1:1, 4:1, 5:3}))
# should print 2
# print(unique_values({0:3, 1:3, 4:3, 5:3}))
# should print 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值