1657614120
Le dictionnaire Python est une structure de données utile pour conserver un enregistrement des paires de clés et de valeurs. De plus, le dictionnaire conserve l'ordre dans lequel les éléments ont été insérés à partir de la version 3.6 et a permis un temps constant pour la récupération des données. Cependant, il ne prend pas en charge l'indexation. Cet article explique comment trier un dictionnaire par clé en Python. Regardons la structure de données du dictionnaire en Python.
La structure de données du dictionnaire contient des données sous la forme de paires clé-valeur. Pour clarifier, imaginez que vous avez un livre. Dans ce cas, ce livre doit avoir un titre et un auteur. Supposons que le titre soit la clé et que l'auteur soit la valeur. Par exemple:
book = {"The Godfather": "Mario Puzo", "Catch-22": "Joseph Heller"}
print(book["The Godfather"])
print(book["Mario Puzo"])
En utilisant la clé du titre du livre, nous pouvons obtenir la valeur de la valeur, ici, le nom de l'auteur. Cependant, l'inverse ne se produira pas car il n'y a pas de clé avec le nom de l'auteur.
Le titre du livre renvoie le nom de l'auteur.
names = {'lil slugger':4, 'marumi':3, 'tuskiko':2,'mitsushiro':1}
names['Masami'] = 6
names['Taeko'] = 5
print(names)
Un dictionnaire de noms avec un nom comme clé et un nombre comme valeur.
L'exemple ci-dessus a imprimé un dictionnaire avec un nom comme clé et un entier comme valeur. Cependant, l'objectif est de trier un dictionnaire par clé en Python.
Examinons différentes manières de trier un dictionnaire par clé en Python. Par exemple:
names_tup = sorted(names.items())
print(names_tup)
sorted_names = {k:v for k,v in names_tup}
print(f'Sorted dictionary: {sorted_names}')
Liste des tuples du dictionnaire des noms de paires clé-valeurpar ordre alphabétique
Passons en revue le fonctionnement du code ci-dessus :
Remarque : Au lieu de stocker le dictionnaire trié dans une autre variable, vous pouvez également le stocker dans la variable d'origine s'il n'est pas utilisé.
La fonction triée fournit un paramètre supplémentaire, à savoir reverse. Le paramètre reverse prend une valeur booléenne. Si false (valeur par défaut), trie l'itérable dans l'ordre croissant ou normal. Cependant, lorsqu'il est vrai, il trie l'itérable dans l'ordre décroissant ou inverse.
names_tup = sorted(names.items(), reverse = True)
sorted_names = {k:v for k,v in names_tup}
print(f'Reverse sorted dictionary: {sorted_names}')
Dictionnaire trié à l'envers
À l'aide de la fonction lambda, nous pouvons spécifier si nous voulons trier un dictionnaire à l'aide de clés ou de valeurs. Par exemple:
names = {'key 1':'lil slugger', 'key 5':'marumi', 'key 2':'tuskiko','key 4':'mitsushiro'}
names['key 6'] = 'Masami'
names['key 5'] = 'Taeko'
names_sort_key = dict(sorted(names.items(), key=lambda item:item[0]))
print(names_sort_key)
Le paramètre clé de la fonction triée prend une fonction. Dans le code ci-dessus, nous avons ajouté une fonction lambda au paramètre clé de la fonction triée. L'item[0] indique la clé du dictionnaire sur laquelle le dictionnaire est trié.
Utilisation de la fonction lambda pour trier le dictionnaire
Itemgetter fait partie du module opérateur de Python, qui est une bibliothèque intégrée. Au lieu de la fonction lambda, itemgetter peut être utilisé pour obtenir un dictionnaire trié sur une clé. Prenons un exemple pour préciser notre propos :
from operator import itemgetter
players = [{'name':'Novak Djokovic', 'rank':1},
{'name':'Daniil Medvedev', 'rank':2},
{'name':'Alexander Zverev', 'rank':4},
{'name':'Matteo Berrettini', 'rank':6},
{'name':'Rafael Nadal', 'rank':3},
{'name':'Stefanos Tsitsipas', 'rank':5}]
# ranked on basis of names
players_names = sorted(players, key=itemgetter('name'))
# ranked on world ranking
players_rank = sorted(players, key=itemgetter('name'))
print(players_names)
print("\n")
print(players_rank)
Dans le code ci-dessus, nous avons pris les 6 meilleurs joueurs de tennis du mot et les avons stockés dans un dictionnaire avec les noms et les rangs comme clés. De plus, la liste du lecteur contient des dictionnaires.
Remarque : La méthode Itemgetter a une implémentation interne globalement différente. Asz un résultat, ce qui le rend plus rapide. De plus, elle est plus concise et lisible que la fonction lambda.
Dictionnaire de tri à l'aide de la méthode itemgetter
Voyons comment nous pouvons trier un dictionnaire sur une clé en utilisant la méthode zip.
names = {'key 1':'lil slugger', 'key 5':'marumi', 'key 2':'tuskiko','key 4':'mitsushiro'}
names['key 6'] = 'Masami'
names['key 5'] = 'Taeko'
sorted_names = dict(sorted(zip(names.keys(),names.values())))
print(sorted_names)
La fonction sorted() trie les clés et les valeurs du dictionnaire individuellement. Ensuite, la méthode zip crée un itérateur qui agrège ou joint les éléments de chaque itérable.
Je trie les dictionnaires en utilisant une méthode zip.
JSON ou JavaScript Object Notation est un format d'échange de données léger. Il est facile pour les humains de lire et d'écrire.
Par exemple, regardons le code suivant à l'aide duquel nous pouvons trier un dictionnaire.
import json
names = {'key 1':'lil slugger', 'key 5':'marumi', 'key 2':'tuskiko','key 4':'mitsushiro'}
names['key 6'] = 'Masami'
names['key 5'] = 'Taeko'
print(json.dumps(names,sort_keys=True))
Utilisation de JSON pour trier les clés d'un dictionnaire
OrderedDict, une sous-classe de dictionnaire, a été introduite dans la version 3.1 de Python dans la bibliothèque standard. C'est une partie du module de collection de Python. En savoir plus ici .
from collections import OrderedDict
names = {'key 1':'lil slugger', 'key 5':'marumi', 'key 2':'tuskiko','key 4':'mitsushiro'}
names['key 6'] = 'Masami'
names['key 5'] = 'Taeko'
names_od = OrderedDict(sorted(names.items()))
print(names_od)
Utiliser OrderedDict pour trier un dictionnaire par clé Python
from datetime import datetime
dates = {
"04-01-2022": "Random text",
"26-10-2022": "More random text",
"31-07-2022": "Some more random text",
}
dates_ordered = dict(sorted(dates.items(), key=lambda x: datetime.strptime(x[0], "%d-%m-%Y")))
print(dates_ordered)
Dictionnaire trié par clé (ici la date)
books = {
"The Godfather": {"author": "Mario Puzo", "release_yr": 1969},
"Catch-22": {"author": "Joseph Heller", "release_yr": 1961},
"The Lighthouse": {"author": "Virginia Woolf", "release_yr": 1927},
"The Fault in Our Stars": {"author": "John Green", "release_yr": 2012},
}
books_sorted = dict(sorted(books.items(), key=lambda x: x[1]["release_yr"]))
print(books_sorted)
Dans le code ci-dessus, nous avons un dictionnaire imbriqué nommé books, contenant le nom du livre, le nom de l'auteur et leurs années de sortie. Après cela, en utilisant la fonction triée et lambda, avec release_yr comme clé, sur laquelle le dictionnaire est ordonné. En conséquence, les livres sont triés par ordre croissant de leurs années de sortie.
Les livres de dictionnaires imbriqués sont triés en fonction de l'année de sortie
Pouvons-nous trier le dictionnaire en gardant le même type de données ?
Vous pouvez trier un dictionnaire en conservant le même type de données à l'aide de la fonction triée.
Pourquoi n'est-il pas recommandé de se fier au tri/ordre du dictionnaire ?
Le dictionnaire avant la version 3.6 de Python n'était pas commandé. Cependant, vous pouvez vous attendre à ce que les éléments conservent l'ordre dans lequel ils ont été insérés.
Le tri est-il inclus par défaut ?
Oui, la fonction triée est déjà incluse dans Python3.
Dans l'article suivant, nous avons couvert les différentes manières de trier un dictionnaire. Par exemple, les fonctions triées et lambda, itemgetter, zip, etc. Ces méthodes peuvent être utiles lorsque vous souhaitez commander vos éléments de dictionnaire.
Source : https://www.pythonpool.com
1619510796
Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.
Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is
Syntax: x = lambda arguments : expression
Now i will show you some python lambda function examples:
#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map
1626775355
No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas.
By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities.
Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly.
Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.
Robust frameworks
Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions.
Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events.
Simple to read and compose
Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building.
The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties.
Utilized by the best
Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player.
Massive community support
Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions.
Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking.
Progressive applications
Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.
The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.
Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential.
The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.
#python development services #python development company #python app development #python development #python in web development #python software development
1620437073
When you write a program in python that particular code is written line by line. Which means there are kind of sentences in your code. These sentences can be identified under two main groups according to the reason why you are adding them into your code.
To make it easy for you I will name them as Python statements and Python comments.
Instructions that you write in your code and that a **Python interpreter **can execute are called statements.
Wait what! Python interpreter? What’s that?
Let me make it clear to you.
Python interpreter is nothing but a converter which converts the Python language to machine language. Your computer’s hardware obviously can’t understand Python. Therefore, there has to be something that makes the computer understand what you want to be done using your Python code. That is basically done by the Python interpreter. Piece of cake!
Still no idea what really Python statements are?
Don’t worry! Help is on the way!
#python-programming #comments-in-python #statements-in-python #python-comments #python-statements
1602968400
Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?
In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.
Swapping value in Python
Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead
>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName
>>> print(FirstName, LastName)
('Jordan', 'kalebu')
#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development
1602666000
Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.
In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.
Heres a solution
Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.
But How do we do it?
If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?
The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.
There’s a variety of hashing algorithms out there such as
#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips