Slovník se používá v mnoha praktických aplikacích, jako je denní programování, vývoj webových aplikací a programování AI/ML, což z něj činí celkově užitečný kontejner. Znalost zkratek pro dosažení různých úkolů souvisejících s používáním slovníku je proto vždy výhodou. Tento článek se zabývá jedním takovým úkolem smazání/odebrání slovníkového páru klíč-hodnota ze slovníku, probereme různé metody řešení daného úkolu a v Posledním uvidíme, jak můžeme odstranit všechny klíče z Slovník .
Příklad:
Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21 } Operation Perform: del test_dict['Mani'] After removing key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}> Metoda 1: Odeberte klíč ze slovníku pomocí příkazu del
Klíčové slovo del lze použít k odstranění klíče, který je přítomen ve slovníku v Pythonu na místě. Jednou nevýhodou, kterou lze použít, je to, že vyvolá výjimku, pokud klíč není nalezen, a proto je třeba řešit neexistenci klíče. Ukázka smazání páru klíč–hodnota pomocí del.
Python3
# Initializing dictionary> test_dict>=> {>'Arushi'>:>22>,>'Mani'>:>21>,>'Haritha'>:>21>}> # Printing dictionary before removal> print>(>'The dictionary before performing remove is : '>, test_dict)> # Using del to remove a dict> # removes Mani> del> test_dict[>'Mani'>]> # Printing dictionary after removal> print>(>'The dictionary after remove is : '>, test_dict)> # Using del to remove a dict> # raises exception> del> test_dict[>'Mani'>]> |
>
>
textový wrapper css
Výstup :
The dictionary before performing remove is : {'Arushi': 22, 'Mani': 21, 'Haritha': 21} The dictionary after remove is : {'Arushi': 22, 'Haritha': 21}> Výjimka:
Traceback (most recent call last): File '/home/44db951e7011423359af4861d475458a.py', line 20, in del test_dict['Mani'] KeyError: 'Mani'>
Časová náročnost inicializace slovníku a odstranění položky ze slovníku pomocí příkazu del je O(1).
Pomocný prostor potřebný pro tento kód je O(1), protože pouze upravujeme stávající slovník a nevytváříme žádné nové datové struktury.
Metoda 2: Odebrání klíče ze slovníku pomocí pop()
The pop() lze použít k odstranění klíče a jeho hodnoty na místě. Výhodou oproti použití del je, že poskytuje mechanismus pro tisk požadované hodnoty, pokud se pokusíte odstranit neexistující příkaz. pár. Za druhé, kromě provedení jednoduché operace odstranění také vrátí hodnotu odstraňovaného klíče. Ukázka odstranění páru klíč–hodnota pomocí pop()
Python3
# Initializing dictionary> test_dict>=> {>'Arushi'>:>22>,>'Anuradha'>:>21>,>'Mani'>:>21>,>'Haritha'>:>21>}> # Printing dictionary before removal> print>(>'The dictionary before performing remove is : '> +> str>(test_dict))> # Using pop() to remove a dict. pair> # removes Mani> removed_value>=> test_dict.pop(>'Mani'>)> # Printing dictionary after removal> print>(>'The dictionary after remove is : '> +> str>(test_dict))> print>(>'The removed key's value is : '> +> str>(removed_value))> print>(>'
'>)> # Using pop() to remove a dict. pair> # doesn't raise exception> # assigns 'No Key found' to removed_value> removed_value>=> test_dict.pop(>'Manjeet'>,>'No Key found'>)> # Printing dictionary after removal> print>(>'The dictionary after remove is : '> +> str>(test_dict))> print>(>'The removed key's value is : '> +> str>(removed_value))> |
>
>
Výstup:
The dictionary before performing remove is : {'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} The dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21} The removed key's value is : 21 The dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21} The removed key's value is : No Key found> Časová složitost: O(1)
Pomocný prostor: O(1)
Metoda 3: Použití položky items() + porozumění diktátu k odstranění klíče ze slovníku
items () ve spojení s porozuměním diktátu nám také může pomoci dosáhnout úkolu odstranění páru klíč-hodnota, ale má nevýhodu v tom, že nejde o diktát na místě. technika. Ve skutečnosti je vytvořen nový diktát kromě klíče, který nechceme zahrnout. Ukázka odstranění páru klíč–hodnota pomocí items() + porozumění diktátu.
Python3
# Initializing dictionary> test_dict>=> {>'Arushi'>:>22>,>'Anuradha'>:>21>,> >'Mani'>:>21>,>'Haritha'>:>21>}> # Printing dictionary before removal> print>('The dictionary before performing> remove>is> : '>+> str>(test_dict))> # Using items() + dict comprehension to remove a dict. pair> # removes Mani> new_dict>=> {key: val>for> key,> >val>in> test_dict.items()>if> key !>=> 'Mani'>}> # Printing dictionary after removal> print>(>'The dictionary after remove is : '> +> str>(new_dict))> |
>
>
Výstup:
The dictionary before performing remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21} The dictionary after remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}> Časová složitost: O(n), kde n je délka seznamu test_dict
Pomocný prostor: Vytvoří se O(n) další prostor o velikosti n, kde n je počet prvků v seznamu res.
Metoda 4: Použití Python Dictionary Comprehension k odebrání klíče ze slovníku
V tomto příkladu použijeme Dictionary Comprehension k odstranění klíče ze slovníku.
Python3
odlévat do provázku
# Initializing dictionary> test_dict>=> {>'Arushi'>:>22>,>'Anuradha'>:>21>,>'Mani'>:>21>,>'Haritha'>:>21>}> # Printing dictionary before removal> print>(>'The dictionary before performing remove is :
'> +> str>(test_dict))> a_dict>=> {key: test_dict[key]>for> key>in> test_dict>if> key !>=> 'Mani'>}> print>(>'The dictionary after performing remove is :
'>, a_dict)> |
>
>
Výstup:
The dictionary before performing remove is : {'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} The dictionary after performing remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21}> Metoda 5: Iterace a eliminace
V tomto příkladu použijeme a smyčka k odstranění klíče ze slovníku.
Python3
# Initializing dictionary> test_dict>=> {>'Arushi'>:>22>,>'Anuradha'>:>21>,>'Mani'>:>21>,>'Haritha'>:>21>}> print>(test_dict)> # empty the dictionary d> y>=> {}> # eliminate the unrequired element> for> key, value>in> test_dict.items():> >if> key !>=> 'Arushi'>:> >y[key]>=> value> print>(y)> |
string.format java řetězec
>
>
Výstup:
{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} {'Anuradha': 21, 'Mani': 21, 'Haritha': 21}> Jak odstranit všechny klíče ze slovníku?
Metoda 1: Odstraňte všechny klíče ze slovníku pomocí příkazu del
Klíčové slovo del lze také použít k odstranění seznamu, rozdělení seznamu, odstranění slovníků, odstranění párů klíč-hodnota ze slovníku, odstranění proměnných atd.
Python3
java míchá do int
# Initializing dictionary> test_dict>=> {>'Arushi'>:>22>,>'Anuradha'>:>21>,>'Mani'>:>21>,>'Haritha'>:>21>}> print>(test_dict)> # empty the dictionary d> del> test_dict> try>:> >print>(test_dict)> except>:> >print>(>'Deleted!'>)> |
>
>
Výstup:
{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} Deleted!> Metoda 2: Odstraňte všechny klíče ze slovníku pomocí dict.clear()
Metoda clear() odstraní všechny položky ze slovníku. Metoda clear() nevrací žádnou hodnotu.
Python3
# Initializing dictionary> test_dict>=> {>'Arushi'>:>22>,>'Anuradha'>:>21>,>'Mani'>:>21>,>'Haritha'>:>21>}> print>(test_dict)> # empty the dictionary d> test_dict.clear()> print>(>'Length'>,>len>(test_dict))> print>(test_dict)> |
>
>
Výstup:
{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} Length 0 {}> Časová složitost: O(1)
Pomocný prostor: O(1)