python字母映射表,将字符串映射到一组字符串的Python字典?

I would like to be able to make a Python dictionary with strings as keys and sets of strings as the values. E.g.: { "crackers" : ["crunchy", "salty"] } It must be a set, not a list.

However, when I try the following:

word_dict = dict()

word_dict["foo"] = set()

word_dict["foo"] = word_dict["foo"].add("baz")

word_dict["foo"] = word_dict["foo"].add("bang")

I get:

Traceback (most recent call last):

File "process_input.py", line 56, in

test()

File "process_input.py", line 51, in test

word_dict["foo"] = word_dict["foo"].add("bang")

AttributeError: 'NoneType' object has no attribute 'add'

If I do this:

word_dict = dict()

myset = set()

myset.add("bar")

word_dict["foo"] = myset

myset.add("bang")

word_dict["foo"] = myset

for key, value in word_dict:

print key,

print value

I get:

Traceback (most recent call last):

File "process_input.py", line 61, in

test()

File "process_input.py", line 58, in test

for key, value in word_dict:

ValueError: too many values to unpack

Any tips on how to coerce Python into doing what I'd like? I'm an intermediate Python user (or so I thought, until I ran into this problem.)

解决方案

set.add() does not return a new set, it modifies the set it is called on. Use it this way:

word_dict = dict()

word_dict["foo"] = set()

word_dict["foo"].add("baz")

word_dict["foo"].add("bang")

Also, if you use a for loop to iterate over a dict, you are iterating over the keys:

for key in word_dict:

print key, word_dict[key]

Alternatively you could iterate over word_dict.items() or word_dict.iteritems():

for key, value in word_dict.items():

print key, value

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值