python dict() 函數使用

dict() 函數用於創建一個字典。

語法

語法:

class dict(**kwargs)
class dict(mapping, **kwargs)
class dict(iterable, **kwargs)

參數說明:

**kwargs -- 關鍵字
mapping -- 元素的容器。
iterable -- 可迭代對象。

返回值

返回一個字典。

示例

# 傳入關鍵字
>>> dict(a='a', b='b', t='t')
{'a': 'a', 'b': 'b', 't': 't'}

# 映射函數方式來構造字典
>>> a = [1,2,3,4]
>>> b = ['a', 'b', 'c', 'd']
>>> ab = zip(a,b)
>>> ab
[(1, u'a'), (2, u'b'), (3, u'c'), (4, u'd')]

>>> dict(ab)
{1: u'a', 2: u'b', 3: u'c', 4: u'd'}

# 可迭代對象方式來構造字典
>>> dict([('one', 1), ('two', 2), ('three', 3)])
{'three': 3, 'two': 2, 'one': 1}

問題

想要變更字典中某一個值,我們使用 dict 來修改,比如,我們想將

{1: u'a', 2: u'b', 3: u'c', 4: u'd'}

中的 {1:u'a'} 修改成 {1: u'aa'},要怎麼做呢?

很顯然,直接使用 dict, 方法如下:

>>> ab_dict = dict(ab)
>>> dict(ab_dict, 1='aa')

結果卻是報錯:

    dict(ab_dict, 1="a")
SyntaxError: keyword can't be an expression

語法上看起來沒有錯,爲什麼會報語法錯誤呢?

原來:

dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)

The keys (or name as used in this case) must be valid Python identifiers, and ints are not valid.

使用 dict 的鍵值對來生成字典時,鍵字必須是 python 中的 標識符,而數字不是標識符。

Identifiers (also referred to as names) are described by the following lexical definitions:
標識符是以下列詞彙的定義

identifier ::= (letter|"_") (letter | digit |"_")
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"

即:標識符必須以字母(大小寫均可)或者"_" 開頭,接下來可以重複 0 到多次(字母|數字|"_")

標識符沒有長度限制,並且區分大小寫

那想要修改怎麼辦,直接通過字典的切片來修改:

>>> ab_dict[1] = 'aa'
>>> ab_dict
{1: u'aa', 2: u'b', 3: u'c', 4: u'd'}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章