Dictionaries

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

How could you create a word dictionary using setdefault?

#create an empty dictionary word_dict = {} #create a for loop that adds words and counts to the dictionary for word in word_list: word_dict.setdefualt(word, 0) word_dict[word] += 1

Dictionaries support what key operations / methods?

- key, value pairs retrieval via dictionary unpacking with .items( ) method. - key and value retrieval with .keys( ) and .values( ) methods respectively.

Common Dictionary Methods

1. dict_obj.items( ) 2. dict_obj.keys( ) 3. dict_obj.values( ) 4. dict_obj.get(key, [default]) 5. dict_obj.setdefault(key, [default]) 6.import collections; collections.Counter(list_obj)

Sets in Python

A set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. A set can be initialized like so: set_name = set( ) # creates an empty set set_name = {elem_1, elem_2, ... } # creates a set with elements set_name = set(list_obj) # makes a set with the elements in a list Note: If there are duplicate values in the list, duplicates are deleted from the set Note2: a set can include mixed data types.

Because of the underlying key hashing mechanisms, dictionaries are optimized for what?

By-key Value Lookups

Dictionaries are not optimized for what operations?

By-value lookups and insertions.

d.get(key, [default])

Description: Get value for key or return default (None) Result: d.get(existing_key) returns associating existing_value d.get(non_existing_key) returns nothing / no output d.get(non_existing_key, None) returns nothing / no output d.get(non_existing_key, other_value) returns other_value

d.setdefault(key, [default])

Description: If key is missing, set to default; else call d.get( ) Result: d.setdefault(existing_key, other_value) returns the associating value for the given key. d.setdefault(non_existing_key, other_value) adds a new key-value pair to the dictionary that has the key, existing_key, and the value, other_value. other_value is returned.

d.keys( )

Description: List of keys Result: dict_keys([key_1, key_2, ... ])

d.values( )

Description: List of values Result: dict_values([value_1, value_2, ... ])

import collections; collections.Counter(list_obj)

Description: Return dictionary of item counts Results: Counter({item_1: count_of_item_1, item_2: count_of_item_2, ... })

d.items( )

Description: List of (key, value) pairs Result: dict_items([(key_1,value_1), (key_2, value_2), ... ])

Dictionary

Dictionary is a mutable mapping of unique keys to values, or a collection of key-value pairs. Another definition would be a ubiquitous, highly optimized built-in data structure in Python. Many constructs such as classes, modules, namespaces are implemented using a dictionary under the cover.

In Operator

In operator can be used to quickly check if a key is inside a dictionary. key in dict_obj returns true if the key is in the dictionary. Else, false is returned.

Index Operations

Indexing is supported using the square bracket literal syntax with a key inside the brackets. dict_obj[key] = value can be used to add and update key-value entries. dict_obj[key] returns the value.

Can key types be mixed?

Key types can be mixed but, it is not desirable. Mixing keys complicates sorting by keys. If key types are mixed, then a key function that explicitly specifies how to compare different types must be provided.

Starting from Python 3.6, keys are ordered by what?

Keys are ordered by insertion order, not alphabetic or numeric order.

Are there any limitations on the types of keys and values you can have?

Keys must be hashable, but values can be any objects. Keys can be of heterogeneous hashable types.

Key Membership Check

The "in" operator to check a dictionary for membership of a key is fast. key_name in dict_obj

The PageRank Algorithm

The google search engine uses the PageRank algorithm, which scores each page based on incoming links. The way it works is that each page initially gets a score of 1. Then, multiple iterations of the algorithm are run, typically ten. For each iteration, one, a page transfers its score divided by the number of outgoing links to each page that it links to. Two, the score transferred is multiplied by a damping factor, typically set to .85.

What happens if you attempt to re-insert an existing key?

There are no duplicate keys in a dictionary. If you attempt to re-insert an existing key, the most recent value of the key overrides the old value.

Dictionaries are designed for fast what?

They are designed for fast lookup of the keys and for fast retrieval of the values associated with the keys.

By-key Value Lookups

To find the value of the dictionary item for a specified key (note that KeyError is produced if a non-existing key is specified): value = dict_obj[key]

By-key Insertions and Updates

To insert the new key or to update the value for the existing key; new key gets appended and/or most recent value overrides the previous value for the same key. dict_obj[new_key] = new_value

Triple Quoted String """ ... """

Triple quotes are treated as regular strings with the exception that they can span multiple lines. If you attempt to write multiple lines using a different type of quote, you will get a syntax error.

Can value types be mixed?

Yes, value types can be heterogeneous (diverse in content).

How would you use collections.Counter to count identical words.

collections.Counter(word_list) and count_words (word_list) produce the same result. Counter({word_1: count_of_word_1, word_2: count_of_word_2, ... }) Make sure to import collections and also from collections import Counter as count_words

Retrieval Operations: Key-Value Pairs

dict_obj.items( ) # returns a list of the key-value pairs Specifically, the following is printed: out[#]: dict_items ([(key_1, value_1), (key_2, value_2), ... ]) The .items( ) operation can also be used to print the key-value pairs as part of a for loop for key,value in dict_obj.items( ) print(key + ' : ' + str(value)) The following is printed: key_1 : value_1 key_2 : value_2 ... etc.

Retrieval Operations: Keys

dict_obj.keys( ) # returns a list of the keys Specifically, the following is printed: out[#]: dict_keys ([key_1, key_2, key_3, ...]) The .keys( ) operation can also be used to print the keys as part of a for loop for key in dict_obj.keys( ) print(key) The following is printed: key_1 key_2 ... etc.

Retrieval Operations: Values

dict_obj.values( ) # returns a list of the values Specifically, the following is printed: out[#]: dict_values ([value_1, value_2, value_3, ...]) The .values( ) operation can also be used to print the values as part of a for loop for value in dict_obj.values( ) print(value) The following is printed: value_1 value_2 ... etc.

How do you do by-key value lookups? How do you produce key errors?

dict_obj[existing_key] # returns the value dict_obj[non-existing_key] # produces a key error

How do you do by-key insertions and / or updates?

dict_obj[new_key] = value # adds a new key-value pair to to the dictionary dict_obj[existing_key] = value # updates the existing key-value pair

How do you initialize a dictionary in Python?

dict_object = {} # Initializing an empty dictionary dict_object = {key_1 : value_1, key_2 : value_2, ... } # Initializing a dictionary with key-value pairs dict_obj = dict(key_1 = value_1, key_2 = value 2, ... ) # Initializing a dictionary with key value pairs # Note that for this syntax, string keys do not require '' but, string values do Ex. d = dict(name='John', age=20)

How would you add unique elements from a list of vectors to a set?

for from_element,to_element in list_obj: set_obj.add(from_element) set_obj.add(to_element) Note: Due to the fact that sets do not contain duplicates, if you attempt to add a element that already exists to the set, then nothing will happen.

How would you print a list of the words and counts from a word count dictionary in a vertical list format where the keys are in alphabetical order?

for key in sorted(word_counts_dict): print(key + ' : ' + str(word_counts_dict[key]))

How would you print a list of the words and counts from a word count dictionary in a vertical list format where the keys are in reverse alphabetical order?

for key in sorted(word_counts_dict, reverse = True): print(key + ' : ' + str(word_counts_dict[key]))

How would you print a list of the words and counts from a word count dictionary in a vertical list format?

for key in word_counts_dict: print(key + ' : ' + str(word_counts_dict[key]))

How would you create a list of vectors?

list_obj = [(from_element_1, to_element_1), (from_element_2, to_element_2), ... )

How would you create a dictionary of "pages" and the number of outgoing links? Note that you are provided a list of vectors where the first element in each vector is the "from page" and the second element is the "to page".

outdegree = {} for from_page,to_page in list_of_vectors: if from_page in outdegree: outdegree[from_page] += 1 else: outdegree[from_page] = 1

How would you create a dictionary of pages and page scores given that the PageRank algorithm runs for 10 iterations and the damping factor is set to .85? Note that you are provided a set of pages and a dictionary of pages and their outdegrees, and a list of vectors depicting links between factors?

page_score = {} # create an empty dictionary for mapping pages and their page ranks for page in pages: page_score[page] = 1 # set the page rank for each page to 1 for i in range(10): for from_page, to_page in list_of_links: page_score[to_page] += ).85 * page_score[from_page} / float(outdegree[from_page]) # for 10 times, for each link in the list of links, the damping factor, 0.85, multiplied by the page score of the from page, divided by the outdegree of the from page is added to the page score of the to page.

String Lower( ) And Upper( ) Method

returns the string as lowercase or upper case

String Replace( ) Method

str_obj.replace('char_1', 'char_2') replaces all instances of char 1 with char 2 in the string, and returns that string. To replace multiple characters in a string one may do str_obj.replace('char_1', 'char_2').replace('char_3', 'char_4') ... etc.

String Strip( ) Method

str_obj.strip('char') This method returns a copy of the string in which the specified char has been stripped from the beginning and end.

String Split( ) Function

string_obj.split() returns the string, string_obj, as a list of words. Space is used as a default delimiter. ['word_1', 'word_2', ... ]

How would you return the number of unique words?

word_dict = collections.Counter(word_list) or word_dict = count_words (word_list) You simply need to return the length of the word counts dictionary. len(word_dict)

Apply Method For Each Letter In A Word List

word_list = [x.method_1().method_2() ... etc. for x in word_list]

Erase Letters From The Beginning And End Of Words In A Word List

word_list = [x.strip.replace('char_1', ' ').replace('char_2, ' ') ... etc. for x in word_list] also can do: word_list = [x.strip('char_1').strip('char_2) ... etc. for x in word_list]

What does print (dict_obj) return?

{key_1 : value_1, key_2 : value_2, ... }


संबंधित स्टडी सेट्स

Pathophysiology Week 2 mechanisms of defense and tissue integrity

View Set

fnan 321 off balance sheet banking

View Set

Life, Health, Annuities - Insurance

View Set

ATI GI System Pharm Made Easy 4.0 Pharm Final

View Set