Dictionary
今天想分享如何用 dictionary 字典方式存資料。
key and Value 如何使用宣槓取直
- collection of of {key:value} pairs
- no duplicate
- allow changeable and ordered
declare dictionary 宣告 dict
It's an unorder , it's not next to each other, so we can't use index like we use in list. Dictionary will have a a key and value look like this:
syntax:
declare:
dictname= {key:value}
get key:print(dictname['key'])
Access and Get value 取我們的直:
1 | dict={ |
取 key 的直: print(dict['keyA'])
=> 1
取所有直 print(dict)
=> {'keyA': 1, 'keyB': 2}
宣告不同 data type
1 | dict={ |
- 取 keyA 的直
print(dict)
output
{‘keyA’: [1, 2, 3], ‘keyB’: ‘hello’, ‘keyC’: True}
- 取 keyA 的第 2 直:
print(dict['keyA'][1])
=>2
- list 裡面放 dict
1 | dict=[{ |
print(dict[0]['keyA'][2])
=>2
Method
Method | Description |
---|---|
clear() | Removes all items from the dictionary. |
copy() | Returns a shallow copy of the dictionary. |
fromkeys(seq[, v]) | Returns a new dictionary with keys from seq and value equal to v (defaults to None). |
get(key[,d]) | Returns the value of the key. If the key does not exist, returns d (defaults to None). |
items() | Return a new object of the dictionary’s items in (key, value) format. |
keys() | Returns a new object of the dictionary’s keys. |
pop(key[,d]) | Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError. |
popitem() | Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty. |
setdefault(key[,d]) | Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None). |
update([other]) | Updates the dictionary with the key/value pairs from other, overwriting existing keys. |
values() | Returns a new object of the dictionary’s values |
Declare Dict
1 | country = { |
key
key need to be immutable, which mean can not change.
1 | print(user['phone']) #123 |
print(dict[123]) #[1,2,3]
print(dict[True]) #hello
print(dict['hi']) #True
If add [100]:True
will occur error because it’s a immutable, can’t change key. list can be change, so we can’t chnage it. Dictionary often use string as it’s key
multiply key
如果有相同的 key,最後一個會被取代 overwrite,因此 key 要 unquie。
As you can see below, if we declare same key, the last key will overwrite the first one, this is why when I print it the last value I show up.
1 | dict={ |
get()
1 | #get value |
get key avoid error when no key exisit
如果我們有 key 用原本語法會有 error,我們可以用 get()方法就不會跳出 error。
get a nonexist key(key 不存在)
print(user['age'])
=>pop error
> >print(user.get("age"))
=>#none
create key with default value
if user don’t have key age, add a default value。建立 key,給予預設直。
print(user.get("age", 55))
=>55
But if if we have key age, then it will ignore 55。
1 | user={ |
keys values items
1 | user={ |
Get() 取 value 的值
1 | country = { |
- get the value
print(country.get("USA"))
output:
WDC
Update 新增與修改
新增 item key and Value,add new item key and value
country.update({"Japan":"TKY"})
>print(country)
output:
{‘USA’: ‘WDC’, ‘China’: ‘BJN’, ‘Taiwan’: ‘TP’, ‘Thailand’: ‘BKK’, ‘Japan’: ‘TYY’}修改 Value,update exist value change exists key
country.update({"Japan":"TTT"})
>print(country)
output:
{‘USA’: ‘WDC’, ‘China’: ‘BJN’, ‘Taiwan’: ‘TP’, ‘Thailand’: ‘BKK’, ‘Japan’: ‘TTT’}
pop and popitem 移除 item
pop 移除
country.pop("Taiwan")
>print(country)
output:
{‘USA’: ‘WDC’, ‘China’: ‘BJN’, ‘Thailand’: ‘BKK’, ‘Japan’: ‘TTT’}popitem:移除最後一組
pop item will remove the latest itemcountry.popitem()
>print(country)
output:
{‘USA’: ‘WDC’, ‘China’: ‘BJN’, ‘Thailand’: ‘BKK’}
clear 清除 empty or clear
country.clear()
>print(country)
output
{}
keys and values (get value or key)
1 | country = { |
- keys
1 | #get the keys |
- values
1 | #get the value |
copy dictionary
1 | countrybk=country.copy() |
Method Example
1 | # Dictionary Methods |
iterate key and value
keys
1 | for key in country.keys(): |
value
1 | for value in country.values(): |
items() keys and values
1 | for key, value in country.items(): |
Dictionary Comprehension
- dictionary = {key: expression for (key,value) in iterable}
- dictionary = {key: expression for (key,value) in iterable if conditional}
- dictionary = {key: (if/else) for (key,value) in iterable}
- dictionary = {key: function(value) for (key,value) in iterable}
using for condition
Syntax:
dictionry={key:expression for (key, value) in iterate}
1 | citiesinF={"Beijing": 20, "Boston":10, "New York":30, "Califorina": 35} |
output:
{‘Beijing’: -7, ‘Boston’: -12, ‘New York’: -1, ‘Califorina’: 2}
using if condition
Syntax:
dictionry={key:expression for (key, value) in iterate if conditional}
1 | weather={"Beijing": "snowing", "Boston":"cloudy", "New York":"sunny"} |
output:
{‘New York’: ‘sunny’}
using if else condition
Syntax:
dictionry={key:if/else for (key, value) in iterate}
1 | citiestemp={"Beijing": 20, "Boston":10, "New York":30, "Califorina": 35} |
output:
{‘Beijing’: ‘warm’, ‘Boston’: ‘cold’, ‘New York’: ‘warm’, ‘Califorina’: ‘warm’}
using function
Syntax:
dictionry={key:function(value)) for (key, value) in iterate}
1 | def checktemp(value): |
output:
{‘Beijing’: ‘cold’, ‘Boston’: ‘cold’, ‘New York’: ‘cool’, ‘Califorina’: ‘cool’}
Example
1 | # Dictionary Comprehension |
Build-In function
Function | Description |
---|---|
all() | Return True if all keys of the dictionary are True (or if the dictionary is empty). |
any() | Return True if all keys of the dictionary are True (or if the dictionary is empty). |
len() | Return the length (the number of items) in the dictionary. |
sorted() | Compares items of two dictionaries. (Not available in Python 3) |
Build-In Example
1 | # Dictionary Built-in Functions |
ALL Examples
Creating Python Dictionary Example
1 | # empty dictionary |
Changing and Adding Dictionary elements
1 | # Changing and adding Dictionary Elements |
Removing elements from Dictionary
1 | # create a dictionary |
Dictionary Operations
1 | # Membership Test for Dictionary Keys |
Iterating Through a Dictionary
- Iterating through a Dictionary
1 | # Iterating through a Dictionary |
- Iterating all keys and values
1 | account = {'eric': 17, 'ben':30} |
- Iterating all keys
1 | account = {'eric': 17, 'ben':30} |
- Iterating all values
1 | account = {'eric': 17, 'ben':30} |
[Amazon test] read file from text file
- Question: Read file into datastucture and search like logfile
If we have a log.txt, as below, you need to and search specfic string, like cat. - log.txt
1 | 1 cat |
- Answer2: using dictionary
1 | d={} |