方法#1: items()+ len()
+リストのスライスを使用する
上記の関数を組み合わせると、この特定のタスクを簡単に実行できます。 2つの部分へのスライスは、リストをスライスすることによって実行され、辞書要素が取得されます items()
出力: 元の辞書:{ ’ CS’:10、’ for’:2、’ is’:4、’ gfg’:6} 方法#2: 出力: 元の辞書:{’CS’:10、’for’:2、’is’:4、’gfg’:6}
#動作を示すPython3コード
#辞書を半分に分割する
#アイテムを使用する()+ len()+リストをスライスする
#辞書を初期化する
test_dict
=
{
’gfg’
:
6
、
’is’
4
、
’for’
:
2
、
’CS’
:
10
}
#元の辞書を印刷
print
(
"元の辞書:"
+
str
(test_dict))
#アイテムの使用()+ len()+リストのスライス
#辞書を半分に分割する
res1
=
dict
(
リスト
(test_dict.items())[
len
(test_dict)
/
/
2
:])
res2
=
dict
(
リスト
<コードクラス="プレーン">(test_dict.items())[:<コードクラス="関数">len<コードクラス="プレーン"> (test_dict) /
/
2
])
#結果を出力
印刷
(
"T辞書の前半: "
+
str
(res1))
print
(
"辞書の後半:"
+
str
(res2))
辞書の前半:{’is’:4、’gfg’:6}
辞書の後半:{’for’:2、’CS’:10} を使用slice()+ len()+ items ()
上記の機能の組み合わせを使用して、この特定のタスクを実行できます。ここでは、上記の方法と同様のタスクを実行しますが、唯一の違いは、リストをスライスする代わりに slave()
を使用してスライス操作を実行することです。
#動作を示すPython3コード
#辞書を半分に分割
#アイテムの使用()+ len()+スライス()
from
itertools
import
islice
#辞書を初期化する
test_dict
=
{
’gfg’
:
6
、
’is’
:
4
’for’
:
2
、
’CS’
:
10
}
#元の辞書を印刷
print
(
"元の辞書:"
+
str
(test_dict))
#アイテムの使用()+ len()+スライス()
#辞書を半分に分割
inc
=
iter
(test _dict.items())
res1
=
dict
( islice (inc、
len
(test_dict)
/
/
2
))
res2
=
dict
(inc)
#結果を出力
印刷
(
"辞書の前半:"
+
str
(res1))
print
(
"Th辞書の後半: "
+
(res2))
辞書の前半:{’is’:4、’gfg’: 6}
辞書の後半:{’for’:2、’CS’:10}