teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

4

追記

2019/01/27 15:57

投稿

hayataka2049
hayataka2049

スコア30939

answer CHANGED
@@ -11,4 +11,16 @@
11
11
  {('eee', 'http://eee'), ('fff', 'http://fff')}
12
12
  >>> dict(s2.items() - s1.items()) # このようにdictに戻す
13
13
  {'eee': 'http://eee', 'fff': 'http://fff'}
14
+ ```
15
+
16
+ ###### 値がunhashableな場合
17
+ ```python
18
+ >>> s1 = {"aaa":["http://aaa"],"bbb":["http://bbb"],"ccc":["http://ccc"],"ddd":["http://ddd"]}
19
+ >>> s2 = {"eee":["http://eee"],"aaa":["http://aaa"],"bbb":["http://bbb"],"fff":["http://fff"]}
20
+ >>> dict(s2.items() - s1.items()) # 同じようには出来ない
21
+ Traceback (most recent call last):
22
+ File "<stdin>", line 1, in <module>
23
+ TypeError: unhashable type: 'list'
24
+ >>> {k:s2[k] for k in s2.keys() - s1.keys()} # keysで集合演算してから辞書内包表記で辞書を作る
25
+ {'eee': ['http://eee'], 'fff': ['http://fff']}
14
26
  ```

3

追記

2019/01/27 15:57

投稿

hayataka2049
hayataka2049

スコア30939

answer CHANGED
@@ -1,4 +1,4 @@
1
- `dict.keys`, `dict.items`で取得できる辞書ビューオブジェクトは集合演算をサポートします。
1
+ `dict.keys`, `dict.items`で取得できる辞書ビューオブジェクトは集合演算をサポートします(ただし`items`は値がすべてhashableという条件付き`list`などが値にある場合は不可能です)。
2
2
 
3
3
  [4. 組み込み型 — Python 3.6.5 ドキュメント | 4.10.1. 辞書ビューオブジェクト](https://docs.python.jp/3/library/stdtypes.html#dictionary-view-objects)
4
4
 

2

valuesは駄目なのかな?

2019/01/27 15:46

投稿

hayataka2049
hayataka2049

スコア30939

answer CHANGED
@@ -1,4 +1,4 @@
1
- `dict.keys`, `dict.values`, `dict.items`で取得できる辞書ビューオブジェクトは集合演算をサポートします。
1
+ `dict.keys`, `dict.items`で取得できる辞書ビューオブジェクトは集合演算をサポートします。
2
2
 
3
3
  [4. 組み込み型 — Python 3.6.5 ドキュメント | 4.10.1. 辞書ビューオブジェクト](https://docs.python.jp/3/library/stdtypes.html#dictionary-view-objects)
4
4
 

1

追記

2019/01/27 15:39

投稿

hayataka2049
hayataka2049

スコア30939

answer CHANGED
@@ -1,4 +1,4 @@
1
- `dict.items`で取得できる辞書ビューオブジェクトは集合演算をサポートします。
1
+ `dict.keys`, `dict.values`, `dict.items`で取得できる辞書ビューオブジェクトは集合演算をサポートします。
2
2
 
3
3
  [4. 組み込み型 — Python 3.6.5 ドキュメント | 4.10.1. 辞書ビューオブジェクト](https://docs.python.jp/3/library/stdtypes.html#dictionary-view-objects)
4
4