Thursday, July 21, 2022

Hip, Woke, Cool: It’s All Fodder For the Oxford Dictionary of African American English - The New York Times - Dictionary

The new lexicon, with Henry Louis Gates Jr. as editor in chief, will collect definitions and histories of words. “The bottom line of the African American people,” Gates said, is “these are people who love language.”

The first time she heard Barbara Walters used the expression “shout out” on television, Tracey Weldon took note.

“I was like, ‘Oh my goodness, it has crossed over!’” said Weldon, a linguist who studies African American English.

English has many words and expressions like “shout out,” she said, which began in Black communities, made their way around the country and then through the English-speaking world. The process has been happening over generations, linguists say, adding an untold number of contributions to the language, including hip, nitty gritty, cool and woke.

Now, a new dictionary — the Oxford Dictionary of African American English — will attempt to codify the contributions and capture the rich relationship Black Americans have with the English language.

A project of Harvard University’s Hutchins Center for African and African American Research and Oxford University Press, the dictionary will not just collect spellings and definitions. It will also create a historical record and serve as a tribute to the people behind the words, said Henry Louis Gates Jr., the project’s editor in chief and the Hutchins Center’s director.

“Just the way Louis Armstrong took the trumpet and turned it inside out from the way people played European classical music,” said Gates, Black people took English and “reinvented it, to make it reflect their sensibilities and to make it mirror their cultural selves.”

The idea was born when Oxford asked Gates to join forces to better represent African American English in its existing dictionaries. Gates instead proposed they do something more ambitious. The project was announced in June, and the first version is expected in three years.

While Oxford’s will not be the first ever dictionary that focuses on African American speech, it will be a well-funded effort — the project has received grants from the Mellon and Wagner Foundations — and will be able to draw on the resources of major institutions.

The dictionary will contain words and phrases that are were originally, predominantly or exclusively used by African Americans, said Danica Salazar, the executive editor for World Englishes for Oxford Languages. That might include a word like “kitchen,” which is a term used to describe the hair that grows at the nape of the neck. Or it could be phrases like “side hustle,” which was created in the Black community and is now widely used.

Some of the research associated with making a dictionary involves figuring out where and when a word originated. To do this, researchers often look to books, magazines and newspapers, Salazar said, because those written documents are easy to date.

Resources could also include books like “Cab Calloway’s Cat-ologue: a Hepster’s Dictionary,” a collection of words used by musicians, including “beat” to mean tired; “Dan Burley’s Original Handbook of Harlem Jive,” published in 1944; and “Black Talk: Words and Phrases from the Hood to the Amen Corner,” published in 1994.

Researchers can look to recorded interviews with formerly enslaved people, Salazar said, and to music, such as the lyrics in old jazz songs. Salazar said the project’s editors also plan to crowdsource information, with call outs on the Oxford website and on social media, asking Black Americans what words they’d like to see in the dictionary and for help with historical documentation.

“Maybe there’s a diary in your grandmother’s attic that has evidence of this word,” Salazar said.

The Oxford English Dictionary has been crowdsourcing since the 19th century, she added. When the first edition was being created, inserts were slipped into books, looking for volunteers to read particular titles, write down phrases they found interesting and mail them back to Oxford. The editor of the O.E.D. received so much mail he got his own postbox set up in front of his house.

Gates explained that the Oxford Dictionary of African American English will not only give the definition of a word, but also describe where it came from and how it emerged.

“You wouldn’t normally think of a dictionary as a way of telling the story of the evolution of the African American people, but it is,” Gates said. “If you sat down and read the dictionary, you’d get a history of the African American people from A to Z.”

Differences in language evolve from separation, said Sonja Lanehart, a professor of linguistics at the University of Arizona and a member of the dictionary advisory board. Those barriers can be geographical, like oceans or mountains, she said, but they can also be social or institutional.

“In this country,” she said, “descendants of Americans who were enslaved, they grew up, they developed, they lived in separate spaces. Even though they were geographically all in, say, Georgia, their lives and communities within those spaces were very different.”

African American English is a variety with its own syntax, word structure and pronunciation features, said Weldon, who is the dean of the graduate school at the University of South Carolina and also a member of the dictionary’s advisory board. But it has long been dismissed as inferior, stigmatized or ignored.

“It is almost never the case that African American English is recognized as even legitimate, much less ‘good’ or something to be lauded,” she said. “And yet it is the lexicon, it is the vocabulary that is the most imitated and celebrated — but not with the African American speech community being given credit for it.”

This dictionary will offer many insights, Gates said, but one overarching lesson jumps out.

“The bottom line of the African American people, when you read this dictionary,” Gates said, “is that you’ll say these are people who love language.”

Adblock test (Why?)

Wednesday, July 20, 2022

How to use Python dictionaries - InfoWorld - Dictionary

Programming languages all come with a variety of data structures, each suited to specific kinds of jobs. Among the data structures built into Python, the dictionary, or Python dict, stands out. A Python dictionary is a fast, versatile way to store and retrieve data by way of a name or even a more complex object type, rather than just an index number.

Python dictionaries consists of one or more keys—an object like a string or an integer. Each key is associated with a value, which can be any Python object. You use a key to obtain its related values, and the lookup time for each key/value pair is highly constant. In other languages, this type of data structure is sometimes called a hash map or associative array.

In this article, we'll walk through the basics of Python dictionaries, including how to use them, the scenarios where they make sense, and some common issues and pitfalls to be aware of.

Working with Python dictionaries

Let's begin with a simple example of a Python dictionary:

movie_years = {
    "2001: a space odyssey": 1968,
    "Blade Runner": 1982
}

In this dictionary, the movie names are the keys, and the release years are the values. The structure {key: value, key: value ... } can be repeated indefinitely.

The example we see here is called a dictionary literal—a dictionary structure that is hard-coded into the program's source. It's also possible to create or modify dictionaries programmatically, as you'll see later on.

Keys in dictionaries

A Python dictionary key can be nearly any Python object. I say "nearly" because the object in question must be hashable, meaning that it must have a hash value (the output of its __hash__() method) that does not change over its lifetime, and which can be compared to other objects.

Any mutable Python object doesn't have a consistent hash value over its lifetime, and so can't be used as a key. For instance, a list can't be a key, because elements can be added to or removed from a list. Likewise, a dictionary itself can't be a key for the same reason. But a tuple can be a key, because a tuple is immutable, and so has a consistent hash across its lifetime.

Strings, numbers (integers and floats alike), tuples, and built-in singleton objects (True, False, and None) are all common types to use as keys.

A given key is unique to a given dictionary. Multiples of the same key aren't possible. If you want to have a key that points to multiple values, you'd use a structure like a list, a tuple, or even another dictionary as the value. (More about this shortly.)

Values in dictionaries

Values in dictionaries can be any Python object at all. Here are some examples of values:

example_values = {
    "integer": 32,
    "float": 5.5,
    "string": "hello world",
    "variable": some_var,
    "object": some_obj,
    "function_output": some_func(),
    "some_list": [1,2,3],
    "another_dict": {
        "Blade Runner": 1982
    }
}

Again, to store multiple values in a key, simply use a container type—a list, dictionary, or tuple—as the value. In the above example, the keys "some_list" and "another_dict" hold lists and dictionaries, respectively. This way, you can create nested structures of any depth needed.

Creating new dictionaries

You can create a new, empty dictionary by simply declaring:

new_dict = {}

You can also use the dict() built-in to create a new dictionary from a sequence of pairs:


new_dict = dict(
    (
        ("integer", 32), ("float", 5.5),
    )
)

Another way to build a dictionary is with a dictionary comprehension, where you specify keys and values from a sequence:


new_dict = {x:x+1 for x in range(3)}
# {0: 1, 1: 2, 2: 3}

Getting and setting dictionary keys and values

To retrieve a value from a dictionary, you use Python's indexing syntax:


example_values["integer"] # yields 32

# Get the year Blade Runner was released
blade_runner_year = movie_years["Blade Runner"]

If you have a container as a value, and you want to retrieve a nested value—that is, something from within the container—you can either access it directly with indexing (if supported), or by using an interstitial assignment:


example_values["another_dict"]["Blade Runner"] # yields 1982
# or ...
another_dict = example_values["another_dict"]
another_dict["Blade Runner"]

# to access a property of an object in a dictionary:
another_dict["some_obj"].property

Setting a value in a dictionary is simple enough:


# Set a new movie and year
movie_years["Blade Runner 2049"] = 2017

Using .get() to safely retrieve dictionary values

If you try to retrieve a value using a key that doesn't exist in a given dictionary, you'll raise a KeyError exception. A common way to handle this sort of retrieval is to use a try/except block. A more elegant way to look for a key that might not be there is the .get() method.

The .get() method on a dictionary attempts to find a value associated with a given key. If no such value exists, it returns None or a default that you specify. In some situations you'll want to explicitly raise an error, but much of the time you'll just want to supply a sane default.


my_dict = {"a":1}

my_dict["b"] # raises a KeyError exception
my_dict.get("a") # returns 1
my_dict.get("b") # returns None
my_dict.get("b", 0) # returns 0, the supplied default

When to use a Python dictionary

Using Python dictionaries makes the most sense under the following conditions:

  • You want to store objects and data using names, not just positions or index numbers. If you want to store elements so that you can retrieve them by their index number, use a list. Note that you can use integers as index keys, but this isn't quite the same as storing data in a list structure, which is optimized for actions like adding to the end of the list. (Dictionaries, as you'll see, have no "end" or "beginning" element as such.)
  • You need to find data and objects quickly by name. Dictionaries are optimized so that lookups for keys are almost always in constant time, regardless of the dictionary size. You can find an element in a list by its position in constant time, too, but you can't hunt for a specific element quickly—you have to iterate through a list to find a specific thing if you don't know its position.
  • The order of elements isn't as important as their presence. Again, if the ordering of the elements matters more than whether or not a given element exists in the collection, use a list. Also, as you'll note below, while dictionaries do preserve the order in which these elements are inserted, that's not the same as being able to seek() to the nth element quickly.

Gotchas for values in dictionaries

There are a few idiosyncrasies worth noting about how values work in dictionaries.

First, if you use a variable name as a value, what's stored under that key is the value contained in the variable at the time the dictionary value was defined. Here's an example:


some_var = 128
example_values = {
    "variable": some_var,
    "function_output": some_func()
}

In this case, we set some_var to the integer 128 before defining the dictionary. The key "variable" would contain the value 128. But if we changed some_var after the dictionary was defined, the contents of the "variable" key would not change. (This rule also applies to Python lists and other container types in Python.)

A similar rule applies to how function outputs work as dictionary values. For the key "function_output", we have some_func(). This means when the dictionary is defined, some_func() is executed, and the returned value is used as the value for "function_output". But some_func() is not re-executed each time we access the key "function_output". That value will remain what it was when it was first created.

If we want to re-run some_func() every time we access that key, we need to take a different approach—one that also has other uses.

Calling function objects in dictionaries

Function objects can be stored in a dictionary as values. This lets us use dictionaries to execute one of a choice of functions based on some key—a common way to emulate the switch/case functionality found in other languages.

First, we store the function object in the dictionary, then we retrieve and execute it:


def run_func(a1, a2):
    ...
def reset_func(a1, a2):
    ...

my_dict = {
    "run": run_func,
    "reset": reset_func
}

command = "run"
# execute run_func
my_dict[command](x, y)
# or ...
cmd = my_dict[command]
cmd(x, y)

Note that we need to define the functions first, then list them in the dictionary.

Also, Python as of version 3.10 has a feature called structural pattern matching that resembles conventional switch/case statements. But in Python, it's meant to be used for matching against structures or combinations of types, not just single values. If you want to use a value to execute an action or just return another value, use a dictionary.

Iterating through dictionaries

If you need to iterate through a dictionary to inspect all of its keys or values, there are a few different ways to do it. The most common is to use a for loop on the dictionary—e.g., for item in the_dict. This yields up the keys in the dictionary, which can then be used to retrieve values if needed:


movie_years = {
    "2001: a space odyssey": 1968,
    "Blade Runner": 1982
}
for movie in movie_years:
    print (movie)

This call would yield "2001: a space odyssey", then "Blade Runner".

If we instead used the following:


for movie in movie_years:
    print (movie_years[movie])

we'd get 1968 and 1982. In this case, we're using the keys to obtain the values.

If we just want the values, we can iterate with the .values() method available on dictionaries:


for value in movie_years.values():

Finally, we can obtain both keys and values together by way of the .items() method:


for key, value in movie_years.items():

Ordering in Python dictionaries

Something you might notice when iterating through dictionaries is that the keys are generally returned in the order in which they are inserted.

This wasn't always the case. Before Python 3.6, items in a dictionary wouldn't be returned in any particular order if you iterated through them. Version 3.6 introduced a new and more efficient dictionary algorithm, which retained insertion order for keys as a convenient side effect.

Previously, Python offered the type collections.OrderedDict as a way to construct dictionaries that preserved insertion order. collections.OrderedDict is still available in the standard library, mainly because a lot of existing software uses it, and also because it supports methods that are still not available with regular dicts. For instance, it offers reversed() to return dictionary keys in reverse order of insertion, which regular dictionaries don't do.

Removing items from dictionaries

Sometimes you need to remove a key/value pair completely from a dictionary. For this, use the del built-in:


del movie_titles["Blade Runner"]

This removes the key/value pair {"Blade Runner": 1982} from our example at the beginning of the article.

Note that setting a key or a value to None is not the same as removing those elements from the dictionary. For instance, the command movie_titles["Blade Runner"] = None would just set the value of that key to None; it wouldn't remove the key altogether.

Finding keys by way of values

A common question with dictionaries is whether it's possible to find a key by looking up a value. The short answer is no—at least, not without iterating through the key/value pairs to find the right value (and thus the right key to go with it).

If you find yourself in a situation where you need to find keys by way of their values, as well as values by way of their keys, consider keeping two dictionaries, where one of them has the keys and values inverted. However, you can't do this if the values you're storing aren't hashable. In a case like that, you'll have to resort to iterating through the dictionary—or, better yet, finding a more graceful solution to the problem you're actually trying to solve.

Dictionaries vs. sets

Finally, Python has another data structure, the set, which superficially resembles a dictionary. Think of it as a dictionary with only keys, but no values. Its syntax is also similar to a dictionary:


movie_titles = {
    "2001: a space odyssey",
    "Blade Runner",
    "Blade Runner 2049"
}

However, sets are not for storing information associated with a given key. They're used mainly for storing hashable values in a way that can be quickly tested for their presence or absence. Also, sets don't preserve insertion order, as the code they use isn't the same as the code used to create dictionaries.

Adblock test (Why?)

Oxford English dictionary (OED) adds 200 east African words - Quartz Africa - Dictionary

The Oxford English Dictionary (OED)—the largest dictionary of the English language—has added 200 new and revised entries from East African English, which are primarily used in Kenya, Tanzania, and Uganda.

In a statement, the OED said coverage of east African English includes the varieties of English spoken in Kenya, Tanzania, and Uganda, three countries that share a common Anglophone background despite their different colonial histories.

The words span from popular street snacks to musical genres in the region.

East African English is influencing the language globally

Nyama choma, which is a favorite across Tanzania and Kenya’s entertainment spots, is meat roasted over an open fire. While chips mayai can be found in any local restaurant in Tanzania and is a mix of omelette and chips. Katogo is a Ugandan breakfast dish using banana.

Local terms for shopping are also included. Mama ntilie, which is a slang term used in Tanzania to describe female vendors who sell street food along the roadside, has been added, along with duka—a local shop selling everything from toiletries to soft drinks.

With the global rise of afrobeats, it’s no wonder that ‘Bongo Flava’ now features in the dictionary. This is a type of music originating from Tanzania and made famous by the country’s biggest artist, Diamond Platnumz.

Daladala—buses which are used across East Africa—is also a new entry. The word comes from ‘dollar’, which is what bus conductors called out as people boarded, and was recreated to ‘daladala.’

Sayings and greetings, which form an important part of east African culture, have been incorporated. While in English, it is typical to say ‘long time no see’ after some time has passed, in Uganda, it is common to say ‘you are lost’, while ‘Well done!’ can also be used as a greeting, particularly when someone is at work.

Swahili language is a huge influence in east Africa

“East Africa has ‘altered (English) to suit its new African surroundings’—to cite Chinua Achebe who was referring to his experience,” said Dr Ida Hadjivayanis, Senior Swahili lecturer at the School of Oriental and African Studies (SOAS).

“I see the language change in my work where through assessing international Swahili exams, I find candidates using the bantu structure with English words, for example ‘kupay’ as opposed to ‘to pay’.”

“This stems from the code switching that is rooted in our experience of living with both Kiswahili and English as well as integrating English into the east African milieu. Hence, greeting someone with ‘umepotea’—‘you are lost’ is common and simply means ‘long time no see’.”

Sheng—Kenya’s beloved urban slang—has also become a popular dialect in the country, mixing English and Swahili, as well as other languages.

“Adopting words of another language is a normal process in the growth and development of  languages,” said Chege Githiora, Professor of Linguistics at Kenyatta University. “In this case, it is a recognition by English of the growing prestige of Swahili as a global language, and the east African culture it embodies.”

“Similarly, English and Arabic (and others) have enriched Swahili which has adopted many words and expressions over the centuries.”

Adblock test (Why?)

Tuesday, July 19, 2022

Oxford English dictionary (OED) adds 200 east African words - Quartz Africa - Dictionary

The Oxford English Dictionary (OED)—the largest dictionary of the English language—has added 200 new and revised entries from East African English, which are primarily used in Kenya, Tanzania, and Uganda.

In a statement, the OED said coverage of east African English includes the varieties of English spoken in Kenya, Tanzania, and Uganda, three countries that share a common Anglophone background despite their different colonial histories.

The words span from popular street snacks to musical genres in the region.

East African English is influencing the language globally

Nyama choma, which is a favorite across Tanzania and Kenya’s entertainment spots, is meat roasted over an open fire. While chips mayai can be found in any local restaurant in Tanzania and is a mix of omelette and chips. Katogo is a Ugandan breakfast dish using banana.

Local terms for shopping are also included. Mama ntilie, which is a slang term used in Tanzania to describe female vendors who sell street food along the roadside, has been added, along with duka—a local shop selling everything from toiletries to soft drinks.

With the global rise of afrobeats, it’s no wonder that ‘Bongo Flava’ now features in the dictionary. This is a type of music originating from Tanzania and made famous by the country’s biggest artist, Diamond Platnumz.

Daladala—buses which are used across East Africa—is also a new entry. The word comes from ‘dollar’, which is what bus conductors called out as people boarded, and was recreated to ‘daladala.’

Sayings and greetings, which form an important part of east African culture, have been incorporated. While in English, it is typical to say ‘long time no see’ after some time has passed, in Uganda, it is common to say ‘you are lost’, while ‘Well done!’ can also be used as a greeting, particularly when someone is at work.

Swahili language is a huge influence in east Africa

“East Africa has ‘altered (English) to suit its new African surroundings’—to cite Chinua Achebe who was referring to his experience,” said Dr Ida Hadjivayanis, Senior Swahili lecturer at the School of Oriental and African Studies (SOAS).

“I see the language change in my work where through assessing international Swahili exams, I find candidates using the bantu structure with English words, for example ‘kupay’ as opposed to ‘to pay’.”

“This stems from the code switching that is rooted in our experience of living with both Kiswahili and English as well as integrating English into the east African milieu. Hence, greeting someone with ‘umepotea’—‘you are lost’ is common and simply means ‘long time no see’.”

Sheng—Kenya’s beloved urban slang—has also become a popular dialect in the country, mixing English and Swahili, as well as other languages.

“Adopting words of another language is a normal process in the growth and development of  languages,” said Chege Githiora, Professor of Linguistics at Kenyatta University. “In this case, it is a recognition by English of the growing prestige of Swahili as a global language, and the east African culture it embodies.”

“Similarly, English and Arabic (and others) have enriched Swahili which has adopted many words and expressions over the centuries.”

Adblock test (Why?)

Python Dictionary: Zero to Hero with Examples | by Amit Chauhan | Jul, 2022 - Medium - Dictionary

Learning dictionary for data science and machine learning applications

Photo by Alex Chumak on Unsplash

Introduction

Python scripts or programs are generally impossible to exist without the use of lists and dictionaries. As we know, dictionaries play a huge role in indexing; we all have already been familiar with the basic concept of Dictionaries from the previous articles. But in this article, we’ll be exploring advanced methods like turning a dictionary into a list or two lists with real-life examples. So let’s have a recap…

What is a Dictionary?

Theoretically, a dictionary is to store data in key-value pairs. And these items are accessed using keys and not their positions, unlike lists. The values in a dictionary can be of any type (string, integers, floating-point numbers, etc.).

Syntax:

A dictionary is defined by an enclosed comma-separated list of key-value pairs in curly braces.

D = {(key):(value),(key):(value),(key):(value),(key):(value)}

Example:

Let’s look at an example of student roll numbers. Consider a dictionary with students’ roll numbers and their names. Practically, there might be many students with the same names. Hence it would be very difficult to get the details. This is where the concept of dictionaries can help us. Each name is stored under a number. So when we search for a number, we get all the details of one student without any mess. You can also enter a new record into a dictionary very easily.

Program Example:

#searching for recordsSearch_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’}print(Search_no[3])
print(Search_no[45])
print(Search_no[20])
Output:
Ashley
Meena
Hari
#entering a new recordSearch_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’}Search_no[1] = “Ashi”
print(Search_no)
Output:{45: ‘Meena’, 56: ‘Raj’, 3: ‘Ashley’, 6: ‘Balu’, 20: ‘Hari’, 1: ‘Ashi’}

Operators in dictionary

Let us now have a look at some of the operators used in Dictionaries.

  • len(D): The len() operator is to return the number of entries stored in the dictionary. In simple words, to get the number of key-value pairs.

Program:

Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’, 77:’Priya’, 78:’Shankar’, 2:’Adhil’}print(len(Search_no))Output:8
  • del D[k]: The ‘del D[k]’ operator is to delete the key along with its value.
Program:Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’, 77:’Priya’, 78:’Shankar’, 2:’Adhil’}del Search_no[2]print(Search_no)Output:{45: ‘Meena’, 56: ‘Raj’, 3: ‘Ashley’, 6: ‘Balu’, 20: ‘Hari’, 77: ‘Priya’, 78: ‘Shankar’}
  • k in D: The ‘k in D’ operator is similar to a true/false statement. If the Key exists then it will return true.
Program:Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’, 77:’Priya’, 78:’Shankar’, 2:’Adhil’}print(45 in Search_no)
print(49 in Search_no)
Output:
True
False
  • k not in D: The ‘k not in D’ operator is similar to a true/false statement. If the key doesn’t exist, it returns the output as false.
Program:Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’, 77:’Priya’, 78:’Shankar’, 2:’Adhil’}print(3 not in Search_no)
print(49 not in Search_no)
Output:
False
True

Important methods in a dictionary

  • Pop and popitem()

pop():

We do know that the pop() method is used to take away a specific element in a list. This method can also be applied to dictionaries. But the difference is that lists are ordered, whereas dictionaries are unordered. Hence pop() will act differently in dictionaries. You can remove a key-value pair by specifying the key in the pop() argument.

Note: KeyError will be raised when the key is not found.

Program:#1Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’, 77:’Priya’, 78:’Shankar’, 2:’Adhil’}search = Search_no.pop(2)
print(Search_no)
Output:
{45: ‘Meena’, 56: ‘Raj’, 3: ‘Ashley’, 6: ‘Balu’, 20: ‘Hari’, 77: ‘Priya’, 78: ‘Shankar’}
#2Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’, 77:’Priya’, 78:’Shankar’}search = Search_no.pop(4)
print(search)
Output:
search = Search_no.pop(4)
KeyError: 4

popitem():

Compared to pop(), popitem() is a little different. This method does not take any argument. But once this method is executed, it removes the last key-value pair present in the dictionary.

Note: KeyError will be raised if popitem() is applied to an empty dictionary.

Program:#1Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’,
6:’Balu’, 20:’Hari’, 77:’Priya’,
78:’Shankar’}
(roll_no, name)= Search_no.popitem()
print(roll_no, name)
Output:
78 Shankar
#2Search_no = {}(roll_no, name)= Search_no.popitem()
print(roll_no, name)
Output:
(roll_no, name)= Search_no.popitem()
KeyError: ‘popitem(): dictionary is empty’

Accessing non-existing keys

In dictionaries, it is evident from the above examples that when we access an element that doesn’t exist, the program would throw an error. Now, this can be prevented easily by using the ‘in’ operator. Let’s see how:

Program:Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’,
6:’Balu’, 20:’Hari’, 77:’Priya’,
78:’Shankar’}
no = 49if no in Search_no:
print(Search_no[no])
else:
print(no, “is not in the dictionary”)
Output:
49 is not in the dictionary

Explanation:

In this program, we are using the if-else condition along with the ‘in’ operator to access elements. If the element we are searching for is present, it will execute the first statement, or else, it will pass the second statement.

Tkinter: Basic GUI Widgets Elements with Python Example

Graphical user interface with tkinker python library

amitprius.medium.com

Numpy Vectorization for Faster Operations With Python

A small comparison of codes between regular and Numpy codes

amitprius.medium.com

copy()

The copy() method is to create a copy of the existing dictionary. This is very handy when you want to play around with the data or make any minor changes to the duplicated dictionary without actually losing or creating the existing dictionary.

Program:Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’}s_no = Search_no.copy()Search_no[45]= “Sheena”
print(s_no)
print(Search_no)
Output:
{45: ‘Meena’, 56: ‘Raj’, 3: ‘Ashley’, 6: ‘Balu’}
{45: ‘Sheena’, 56: ‘Raj’, 3: ‘Ashley’, 6: ‘Balu’}

Explanation:

The above program shows us how to make a copy of a dictionary by changing one of the values.

Now, the problem with this copy() method is that it’s a shallow copy. If the value in a dictionary is complex like lists, then the in-places changes in this object and can also affect the copy as well. Let’s look at an example:

Program 1:Students = { “Meena”:{“Subject”:”English”, “Marks”: 69},
“Raj”:{“Subject”:”Maths”, “Marks”: 80},
“Sharon”:{“Subject”:”Science”, “Marks”: 96}}
Students2 = Students.copy()Students[“Meena”][“Marks”] = 98print(Students)
print(Students2)
Output:{‘Meena’: {‘Subject’: ‘English’, ‘Marks’: 98}, ‘Raj’: {‘Subject’: ‘Maths’, ‘Marks’: 80}, ‘Sharon’:{‘Subject’: ‘Science’, ‘Marks’: 96}}{‘Meena’: {‘Subject’: ‘English’, ‘Marks’: 98}, ‘Raj’: {‘Subject’: ‘Maths’, ‘Marks’: 80},‘Sharon’: {‘Subject’: ‘Science’, ‘Marks’: 96}}

Explanation:

What happens here is that, when handling complex dictionaries, the changes made in the original have been reflected in the copy as well. You can see that when one of the values of the original dictionary: “Students”, is changed to 98, the value in the copy has also been updated. Let’s see how to avoid this:

Program 2:Students = { “Meena”:{“Subject”:”English”, “Marks”: 69},
“Raj”:{“Subject”:”Maths”, “Marks”: 80},
“Sharon”:{“Subject”:”Science”, “Marks”: 96}}
Students2 = Students.copy()Students[“Meena”] = {“Subject”:”English”, “Marks”: 98}print(Students)
print(Students2)
Output:{‘Meena’: {‘Subject’: ‘English’, ‘Marks’: 98}, ‘Raj’: {‘Subject’: ‘Maths’, ‘Marks’: 80}, ‘Sharon’: {‘Subject’: ‘Science’, ‘Marks’: 96}}{‘Meena’: {‘Subject’: ‘English’, ‘Marks’: 69}, ‘Raj’: {‘Subject’: ‘Maths’, ‘Marks’: 80}, ‘Sharon’: {‘Subject’: ‘Science’, ‘Marks’: 96}}

Explanation:

To avoid changes being made to the copy, all you have to do is, enter the entire dictionary that you want to make the change. In this case, we are making changes to only the “Meena” dictionary. Hence, assign the updated information of that entire dictionary alone.

clear()

The clear() method is nothing but to clear the content of a dictionary. Using this method will not delete the dictionary but will just set it to an empty dictionary.

Program:Students = { “Meena”:{“Subject”:”English”, “Marks”: 69},
“Raj”:{“Subject”:”Maths”, “Marks”: 80},
“Sharon”:{“Subject”:”Science”, “Marks”: 96}}
Students.clear()
print(Students)
Output:{}

update()

The update() method is to merge two different dictionaries into one. This means it merges the key values of one dictionary into another by overwriting the values of the exact key.

Program:Search_no_1 = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’}
Search_no_2 = {45:’Alok’, 33:’Shyam’, 5:’Aliya’, 70:’Sho’}
Search_no_1.update(Search_no_2)
print(Search_no_1)
Output:
{45: ‘Alok’, 56: ‘Raj’, 3: ‘Ashley’, 6: ‘Balu’, 33: ‘Shyam’, 5: ‘Aliya’, 70: ‘Sho’}

Explanation:

As you can see, in the above program, we have created 2 separate dictionaries — Search_no_1 and Search_no_2. We are then using the update() method -“Search_no_1.update(Search_no_2)”. This means that all the key-value pairs of the Search_no_2 dictionary get merged into the Search_no_1 dictionary. Also, the key-value “45:’Meena’” gets updated to “45:’Alok’” (highlighted in black).

Iterate over dictionaries

Coming to iteration, there are only two methods you actually need to iterate over a dictionary. Let’s take a look:

key(), value()

Program:

dic = {“x”:56, “y”:22, “z”:50}for key in dic:
print(key)
for value in dic.values():
print(value)
Output:
x
y
z
56
22
50

Explanation:

In the above program, we are using a for loop to iterate all the keys and values in the dictionary. Using the for loop, we are mainly using two methods: key() and value(). The key() method will only return the keys of the dictionary, and the value() method will only return the values of the dictionary.

Connection between lists and dictionaries

As discussed in the beginning, lists and dictionaries are very efficient in Python program. So, once you get familiar with these two concepts, you might have thought about whether you can change lists to dictionaries or dictionaries to lists. The answer is yes! Let’ see:

Turning dictionaries into lists

Converting a dictionary to a list can be done using only three methods:

item(), keys(), values()

Program:

dic = {“x”:56, “y”:22, “z”:50}item_d = dic.items()
items = list(item_d)
print(items)keys_d = dic.keys()
keys = list(keys_d)
print(keys)values_d = dic.values()
values = list(values_d)
print(values)Output:
[(‘x’, 56), (‘y’, 22), (‘z’, 50)]
[‘x’, ‘y’, ‘z’]
[56, 22, 50]

Explanation:

In the above program, we have converted a dictionary into a list in three different ways. The first way: we use the item() method that returns a dictionary’s key-value pair in the form of a tuple. After this, we are using the list() method to convert the created tuple to a list.

The second way is by using the key() method followed by the list(). And the third way is by using the values() method followed by a list().

Turning lists into dictionaries

You saw how to convert a dictionary to a list. Let’s now do the opposite. To convert a list to a dictionary, we use two methods:

dict(), zip()

Program:

li = [“x”, “y”, “z”, “w”]
ti = [“a”, “b”, “c”]
dic = dict(zip(li, ti))
print(dic)
Output:
{‘x’: ‘a’, ‘y’: ‘b’, ‘z’: ‘c’}

Explanation:

Our main goal in this program is to create a dictionary with the key and values from the two lists. So, our first step is to create two lists. After this, we are using the zip() and dict() methods to convert the list to dictionaries. The zip() function is to return a zip object, where the first item, second item, and so on are paired together. The dict() function is a function to create a dictionary. And finally, we are printing the result where we obtain the output as shown.

Conclusion:

In conclusion, this article has covered some of the advanced concepts of Dictionaries. I strongly recommend experimenting with these methods by applying them in real-time projects using python.

I hope you like the article. Reach me on my LinkedIn and twitter.

Recommended Articles

1. 15 Most Usable NumPy Methods with Python
2. NumPy: Linear Algebra on Images
3. Exception Handling Concepts in Python
4. Pandas: Dealing with Categorical Data
5. Hyper-parameters: RandomSeachCV and GridSearchCV in Machine Learning
6. Fully Explained Linear Regression with Python
7. Fully Explained Logistic Regression with Python
8. Data Distribution using Numpy with Python
9. 40 Most Insanely Usable Methods in Python
10. 20 Most Usable Pandas Shortcut Methods in Python

Adblock test (Why?)

Monday, July 18, 2022

Python Dictionary: Zero to Hero with Examples | by Amit Chauhan | Jul, 2022 - Medium - Dictionary

Learning dictionary for data science and machine learning applications

Photo by Alex Chumak on Unsplash

Introduction

Python scripts or programs are generally impossible to exist without the use of lists and dictionaries. As we know, dictionaries play a huge role in indexing; we all have already been familiar with the basic concept of Dictionaries from the previous articles. But in this article, we’ll be exploring advanced methods like turning a dictionary into a list or two lists with real-life examples. So let’s have a recap…

What is a Dictionary?

Theoretically, a dictionary is to store data in key-value pairs. And these items are accessed using keys and not their positions, unlike lists. The values in a dictionary can be of any type (string, integers, floating-point numbers, etc.).

Syntax:

A dictionary is defined by an enclosed comma-separated list of key-value pairs in curly braces.

D = {(key):(value),(key):(value),(key):(value),(key):(value)}

Example:

Let’s look at an example of student roll numbers. Consider a dictionary with students’ roll numbers and their names. Practically, there might be many students with the same names. Hence it would be very difficult to get the details. This is where the concept of dictionaries can help us. Each name is stored under a number. So when we search for a number, we get all the details of one student without any mess. You can also enter a new record into a dictionary very easily.

Program Example:

#searching for recordsSearch_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’}print(Search_no[3])
print(Search_no[45])
print(Search_no[20])
Output:
Ashley
Meena
Hari
#entering a new recordSearch_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’}Search_no[1] = “Ashi”
print(Search_no)
Output:{45: ‘Meena’, 56: ‘Raj’, 3: ‘Ashley’, 6: ‘Balu’, 20: ‘Hari’, 1: ‘Ashi’}

Operators in dictionary

Let us now have a look at some of the operators used in Dictionaries.

  • len(D): The len() operator is to return the number of entries stored in the dictionary. In simple words, to get the number of key-value pairs.

Program:

Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’, 77:’Priya’, 78:’Shankar’, 2:’Adhil’}print(len(Search_no))Output:8
  • del D[k]: The ‘del D[k]’ operator is to delete the key along with its value.
Program:Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’, 77:’Priya’, 78:’Shankar’, 2:’Adhil’}del Search_no[2]print(Search_no)Output:{45: ‘Meena’, 56: ‘Raj’, 3: ‘Ashley’, 6: ‘Balu’, 20: ‘Hari’, 77: ‘Priya’, 78: ‘Shankar’}
  • k in D: The ‘k in D’ operator is similar to a true/false statement. If the Key exists then it will return true.
Program:Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’, 77:’Priya’, 78:’Shankar’, 2:’Adhil’}print(45 in Search_no)
print(49 in Search_no)
Output:
True
False
  • k not in D: The ‘k not in D’ operator is similar to a true/false statement. If the key doesn’t exist, it returns the output as false.
Program:Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’, 77:’Priya’, 78:’Shankar’, 2:’Adhil’}print(3 not in Search_no)
print(49 not in Search_no)
Output:
False
True

Important methods in a dictionary

  • Pop and popitem()

pop():

We do know that the pop() method is used to take away a specific element in a list. This method can also be applied to dictionaries. But the difference is that lists are ordered, whereas dictionaries are unordered. Hence pop() will act differently in dictionaries. You can remove a key-value pair by specifying the key in the pop() argument.

Note: KeyError will be raised when the key is not found.

Program:#1Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’, 77:’Priya’, 78:’Shankar’, 2:’Adhil’}search = Search_no.pop(2)
print(Search_no)
Output:
{45: ‘Meena’, 56: ‘Raj’, 3: ‘Ashley’, 6: ‘Balu’, 20: ‘Hari’, 77: ‘Priya’, 78: ‘Shankar’}
#2Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’, 20:’Hari’, 77:’Priya’, 78:’Shankar’}search = Search_no.pop(4)
print(search)
Output:
search = Search_no.pop(4)
KeyError: 4

popitem():

Compared to pop(), popitem() is a little different. This method does not take any argument. But once this method is executed, it removes the last key-value pair present in the dictionary.

Note: KeyError will be raised if popitem() is applied to an empty dictionary.

Program:#1Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’,
6:’Balu’, 20:’Hari’, 77:’Priya’,
78:’Shankar’}
(roll_no, name)= Search_no.popitem()
print(roll_no, name)
Output:
78 Shankar
#2Search_no = {}(roll_no, name)= Search_no.popitem()
print(roll_no, name)
Output:
(roll_no, name)= Search_no.popitem()
KeyError: ‘popitem(): dictionary is empty’

Accessing non-existing keys

In dictionaries, it is evident from the above examples that when we access an element that doesn’t exist, the program would throw an error. Now, this can be prevented easily by using the ‘in’ operator. Let’s see how:

Program:Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’,
6:’Balu’, 20:’Hari’, 77:’Priya’,
78:’Shankar’}
no = 49if no in Search_no:
print(Search_no[no])
else:
print(no, “is not in the dictionary”)
Output:
49 is not in the dictionary

Explanation:

In this program, we are using the if-else condition along with the ‘in’ operator to access elements. If the element we are searching for is present, it will execute the first statement, or else, it will pass the second statement.

Tkinter: Basic GUI Widgets Elements with Python Example

Graphical user interface with tkinker python library

amitprius.medium.com

Numpy Vectorization for Faster Operations With Python

A small comparison of codes between regular and Numpy codes

amitprius.medium.com

copy()

The copy() method is to create a copy of the existing dictionary. This is very handy when you want to play around with the data or make any minor changes to the duplicated dictionary without actually losing or creating the existing dictionary.

Program:Search_no = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’}s_no = Search_no.copy()Search_no[45]= “Sheena”
print(s_no)
print(Search_no)
Output:
{45: ‘Meena’, 56: ‘Raj’, 3: ‘Ashley’, 6: ‘Balu’}
{45: ‘Sheena’, 56: ‘Raj’, 3: ‘Ashley’, 6: ‘Balu’}

Explanation:

The above program shows us how to make a copy of a dictionary by changing one of the values.

Now, the problem with this copy() method is that it’s a shallow copy. If the value in a dictionary is complex like lists, then the in-places changes in this object and can also affect the copy as well. Let’s look at an example:

Program 1:Students = { “Meena”:{“Subject”:”English”, “Marks”: 69},
“Raj”:{“Subject”:”Maths”, “Marks”: 80},
“Sharon”:{“Subject”:”Science”, “Marks”: 96}}
Students2 = Students.copy()Students[“Meena”][“Marks”] = 98print(Students)
print(Students2)
Output:{‘Meena’: {‘Subject’: ‘English’, ‘Marks’: 98}, ‘Raj’: {‘Subject’: ‘Maths’, ‘Marks’: 80}, ‘Sharon’:{‘Subject’: ‘Science’, ‘Marks’: 96}}{‘Meena’: {‘Subject’: ‘English’, ‘Marks’: 98}, ‘Raj’: {‘Subject’: ‘Maths’, ‘Marks’: 80},‘Sharon’: {‘Subject’: ‘Science’, ‘Marks’: 96}}

Explanation:

What happens here is that, when handling complex dictionaries, the changes made in the original have been reflected in the copy as well. You can see that when one of the values of the original dictionary: “Students”, is changed to 98, the value in the copy has also been updated. Let’s see how to avoid this:

Program 2:Students = { “Meena”:{“Subject”:”English”, “Marks”: 69},
“Raj”:{“Subject”:”Maths”, “Marks”: 80},
“Sharon”:{“Subject”:”Science”, “Marks”: 96}}
Students2 = Students.copy()Students[“Meena”] = {“Subject”:”English”, “Marks”: 98}print(Students)
print(Students2)
Output:{‘Meena’: {‘Subject’: ‘English’, ‘Marks’: 98}, ‘Raj’: {‘Subject’: ‘Maths’, ‘Marks’: 80}, ‘Sharon’: {‘Subject’: ‘Science’, ‘Marks’: 96}}{‘Meena’: {‘Subject’: ‘English’, ‘Marks’: 69}, ‘Raj’: {‘Subject’: ‘Maths’, ‘Marks’: 80}, ‘Sharon’: {‘Subject’: ‘Science’, ‘Marks’: 96}}

Explanation:

To avoid changes being made to the copy, all you have to do is, enter the entire dictionary that you want to make the change. In this case, we are making changes to only the “Meena” dictionary. Hence, assign the updated information of that entire dictionary alone.

clear()

The clear() method is nothing but to clear the content of a dictionary. Using this method will not delete the dictionary but will just set it to an empty dictionary.

Program:Students = { “Meena”:{“Subject”:”English”, “Marks”: 69},
“Raj”:{“Subject”:”Maths”, “Marks”: 80},
“Sharon”:{“Subject”:”Science”, “Marks”: 96}}
Students.clear()
print(Students)
Output:{}

update()

The update() method is to merge two different dictionaries into one. This means it merges the key values of one dictionary into another by overwriting the values of the exact key.

Program:Search_no_1 = {45:’Meena’, 56:’Raj’, 3:’Ashley’, 6:’Balu’}
Search_no_2 = {45:’Alok’, 33:’Shyam’, 5:’Aliya’, 70:’Sho’}
Search_no_1.update(Search_no_2)
print(Search_no_1)
Output:
{45: ‘Alok’, 56: ‘Raj’, 3: ‘Ashley’, 6: ‘Balu’, 33: ‘Shyam’, 5: ‘Aliya’, 70: ‘Sho’}

Explanation:

As you can see, in the above program, we have created 2 separate dictionaries — Search_no_1 and Search_no_2. We are then using the update() method -“Search_no_1.update(Search_no_2)”. This means that all the key-value pairs of the Search_no_2 dictionary get merged into the Search_no_1 dictionary. Also, the key-value “45:’Meena’” gets updated to “45:’Alok’” (highlighted in black).

Iterate over dictionaries

Coming to iteration, there are only two methods you actually need to iterate over a dictionary. Let’s take a look:

key(), value()

Program:

dic = {“x”:56, “y”:22, “z”:50}for key in dic:
print(key)
for value in dic.values():
print(value)
Output:
x
y
z
56
22
50

Explanation:

In the above program, we are using a for loop to iterate all the keys and values in the dictionary. Using the for loop, we are mainly using two methods: key() and value(). The key() method will only return the keys of the dictionary, and the value() method will only return the values of the dictionary.

Connection between lists and dictionaries

As discussed in the beginning, lists and dictionaries are very efficient in Python program. So, once you get familiar with these two concepts, you might have thought about whether you can change lists to dictionaries or dictionaries to lists. The answer is yes! Let’ see:

Turning dictionaries into lists

Converting a dictionary to a list can be done using only three methods:

item(), keys(), values()

Program:

dic = {“x”:56, “y”:22, “z”:50}item_d = dic.items()
items = list(item_d)
print(items)keys_d = dic.keys()
keys = list(keys_d)
print(keys)values_d = dic.values()
values = list(values_d)
print(values)Output:
[(‘x’, 56), (‘y’, 22), (‘z’, 50)]
[‘x’, ‘y’, ‘z’]
[56, 22, 50]

Explanation:

In the above program, we have converted a dictionary into a list in three different ways. The first way: we use the item() method that returns a dictionary’s key-value pair in the form of a tuple. After this, we are using the list() method to convert the created tuple to a list.

The second way is by using the key() method followed by the list(). And the third way is by using the values() method followed by a list().

Turning lists into dictionaries

You saw how to convert a dictionary to a list. Let’s now do the opposite. To convert a list to a dictionary, we use two methods:

dict(), zip()

Program:

li = [“x”, “y”, “z”, “w”]
ti = [“a”, “b”, “c”]
dic = dict(zip(li, ti))
print(dic)
Output:
{‘x’: ‘a’, ‘y’: ‘b’, ‘z’: ‘c’}

Explanation:

Our main goal in this program is to create a dictionary with the key and values from the two lists. So, our first step is to create two lists. After this, we are using the zip() and dict() methods to convert the list to dictionaries. The zip() function is to return a zip object, where the first item, second item, and so on are paired together. The dict() function is a function to create a dictionary. And finally, we are printing the result where we obtain the output as shown.

Conclusion:

In conclusion, this article has covered some of the advanced concepts of Dictionaries. I strongly recommend experimenting with these methods by applying them in real-time projects using python.

I hope you like the article. Reach me on my LinkedIn and twitter.

Recommended Articles

1. 15 Most Usable NumPy Methods with Python
2. NumPy: Linear Algebra on Images
3. Exception Handling Concepts in Python
4. Pandas: Dealing with Categorical Data
5. Hyper-parameters: RandomSeachCV and GridSearchCV in Machine Learning
6. Fully Explained Linear Regression with Python
7. Fully Explained Logistic Regression with Python
8. Data Distribution using Numpy with Python
9. 40 Most Insanely Usable Methods in Python
10. 20 Most Usable Pandas Shortcut Methods in Python

Adblock test (Why?)