python字典和结构化数据

栏目: Python · 发布时间: 6年前

内容简介:字典的索引可以使用许多不同类型的数据,不只是整数。字典的索引被称为“键”,键及其关联的值称为“键—值”对,在代码中,字典输入时带花括号{}。字典中的表项是不排序的,所以字典不能像列表那样切片。

5.1  字典数据类型

字典的索引可以使用许多不同类型的数据,不只是整数。字典的索引被称为“键”,键及其关联的值称为“键—值”对,在代码中,字典输入时带花括号{}。

字典中的表项是不 排序 的,所以字典不能像列表那样切片。

5.1.1 keys()、values()和items()方法

key()、values()和items()方法将返回类似于列表的值,分别对应于字典的键、值和键-值对。这些方法返回的值不是真正的列表,他们不能被修改,没有append()方法。但这些数据类型可以用于for循环。

>>> spam = {'color':'red','age':42} >>> for i in spam.values(): print (i)

red 42

可以通过list()方法将字典转换为列表

>>> list(spam.keys())
['color', 'age'] >>> list(spam.values())
['red', 42] >>> spam
{'color': 'red', 'age': 42}

5.1.2 get()方法setdefault()方法

get()方法有两个参数:要取得其值的键,以及如果该键不存在时,返回的备用值

setdefault()方法提供了一种方式,传递给该方法的第一个参数,是要检查的键,第二个参数,是如果该键不存在时要设置的值。如果该键存在就返回键值。

如果程序中导入了pprint()模块,就可以使用pprint()和pformat()打印字典。

import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.' count = {} for character in message: count.setdefault(character, 0) count[character] = count[character] + 1 print(pprint.pformat(count)) #pprint.pprint(count)  print(pprint.pformat(count))这两种表达式等价

运行结果:

{' ': 13, ',': 1, '.': 1, 'A': 1, 'I': 1, 'a': 4, 'b': 1, 'c': 3, 'd': 3, 'e': 5, 'g': 2, 'h': 3, 'i': 6, 'k': 2, 'l': 3, 'n': 4, 'o': 2, 'p': 1, 'r': 5, 's': 3, 't': 6, 'w': 2, 'y': 1}

5.2  实践项目

  1. 好玩游戏的物品清单

你在创建一个好玩的视频游戏。用于对玩家物品清单建模的数据结构是一个字典。其中键是字符串,描述清单中的物品,值是一个整型值,说明玩家有多少该物品。例如,字典值{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1,'arrow': 12}意味着玩家有 1 条绳索、6 个火把、42 枚金币等。 写一个名为displayInventory()的函数,它接受任何可能的物品清单,并显示如下:

Inventory: 1 rop 6 torch 42 gold coin 1 dagger 12 arrow Total number of items :  62

代码如下:

def displayInventory(dic): print('Inventory:') count = 0 for k, v in dic.items(): print(str(v) + ' ' + k) count = v+count print('Total number of items : ', count)


dicValue = {'rop': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
displayInventory(dicValue)
  1. 假设征服一条龙的战利品表示为这样的字符串列表:
dragonLoot = ['gold coin', 'digger', 'gold coin', 'gold coin', 'ruby']

写一个名为 addToInventory(inventory, addedItems)的函数,其中 inventory 参数 是一个字典,表示玩家的物品清单(像前面项目一样),addedItems 参数是一个列表, 就像 dragonLoot。 addToInventory()函数应该返回一个字典,表示更新过的物品清单。

def displayInventory(dic): print('Inventory:')
    count = 0 for k, v in dic.items():
        print(str(v) + ' ' + k)
        count = v+count
    print('Total number of items : ', count) def addToInventory(inventory, addeditems): for i in addeditems: if i in inventory.keys():
            inventory[i] += 1 else:
            inventory.setdefault(i, 1) return inventory


inv = {'gold coin':42, 'rope':1}
dragonLoot = ['gold coin', 'digger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv,dragonLoot)
displayInventory(inv)

前面的程序(加上前一个项目中的 displayInventory()函数)将输出如下:

Inventory: 45 gold coin 1 rope 1 digger 1 ruby Total number of items :  48

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

疯狂的站长

疯狂的站长

温世豪 / 清华大学出版社 / 2010年05月 / 29.00元

受全球性金融危机的影响,就业变得越来越困难,众多青年,包括大学毕业生,无不感到就业的巨大压力,站长这一职业不但创业门槛低,而且还自由自在。其实,搭建一个网站是相当简单的,但要成为一名成功的站长则不那么容易。 本书作者是一名站长,从事互联网相关工作已十余年,自已也在经营一个知名网站,积累了大量网站运营经验。作者结合自身真实的“疯狂”创业经历,以平实、通俗的语言讲述如何从零开始起步,最终成为一名......一起来看看 《疯狂的站长》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具