Quick Dict

Quick Dict

Quick Dict

This is a very quick lookup tool to check the validity of words within a 250,000 word English dictionary. It maintains a very small windows size so you can keep it active when you want. It is completely resizable simply by dragging any of the window edges. You also have the ability to keep the window always on top so it doesn’t get hidden by full screen applications.

An extremely useful tool while playing any sort of word or puzzle games. A simple way to see if a word exists in the English language. Version 1.0.1 may include unspecified updates, enhancements, or bug fixes.

WHAT’S NEW IN VERSION 1.0.1
Version 1.0.1 may include unspecified updates, enhancements, or bug fixes.
GENERAL
Release
November 7, 2008
Date Added
June 19, 2007
Version
1.0.1
OPERATING SYSTEMS
Operating Systems
Windows 2000, Windows Vista, Windows, Windows XP, Windows NT
Additional Requirements
Windows NT/2000/XP/Vist

Download and extract the extension
Navigate to chrome://extensions (via omnibox or Menu -> Tools -> Extensions)
Enable the Developer mode in the upper right corner
Click on “Load unpacked extension…”
Select the directory containing the unpacked extension
How to use
You can either start a search by clicking on the extension icon or by pressing <ctrl + space> on the keyboard, then type in the word or phrase you are looking for and press <enter>. If any text is selected when the popup window opens, quick-dict will automatically go ahead and use that text to search for a translation on dict.cc.

Limitations
Since there is no options page implemented yet, the only way to change its behaviour is by modifing the source code itself.

By default only English-German or German-English translations are supported. To change the source and target language simply change the subdomain of the query URL in popup.js > lookUp() according to: https://<COUNTRY_CODE_1>-<COUNTRY_CODE_2>.dict.cc/?s=<TARGET_STRING> (e.g.: https://en-it.dict.cc/?s=play). To see a list of all possible language combinations visit dict.cc and click on the dropdown below the search field.
The keyboard shortcut can be set inside manifest.json under commands (default is <ctrl + space>).
Only the first result page is currently shown in the popup window
About
Simple Chrome Extension to get quick German to English translations from www.dict.cc

Topics
chrome-extensions
Resources
Readme
License
GPL-3.0 License
Stars
0 stars
Watchers
1 watching
Forks
0 forks
Releases
No releases published
Packages
No packages published
Languages
CSS
72.2%

JavaScript
19.6%

HTML
8.2%
© 2022 GitHub, Inc.
Terms

You are here: Home / Dictionary / Python Dictionary Quick Guide
Python Dictionary Quick Guide
Author: PFB Staff Writer
Last Updated: June 6, 2020

As the title says, this is a Python dictionary quick guide.

Please check out the Dictionary Tutorial for more articles about dictionaries.

# key/value pairs declaration
dict = {
‘key1′:’value1′,
‘key2′:’value2′,
‘key3′:’value3′
}

#Get all keys
dict.keys()

#Get all values
dict.values()

#Modifying
dict[‘key2’] = ‘value8′

#Accessing
print dict[‘key1’]

# prints ‘value2′
print dict[‘key2’]

# empty declaration + assignment of key-value pair
emptyDict = {}
emptyDict[‘key4’]=’value4′

# looping through dictionaries (keys and values)
for key in dict:
print dict[key]

# sorting keys and accessing their value in order
keys = dict.keys()
keys.sort()
for key in keys:
print dict[key]

# looping their values directory (not in order)
for value in dict.values():
print value

# getting both the keys and values at once
for key,value in dict.items():
print “%s=%s” % (key,value)

# deleting an entry
del dict[‘key2’]

# delete all entries in a dictionary
dict.clear()

# size of the dictionary
len(dict)
Related
Reverse A Dictionary in Python
March 8, 2022
In “Basics”
Empty a Dictionary in Python
March 9, 2022
In “Basics”
Append a New Row in a Dataframe in Python
March 11, 2022
In “Basics”

Advertisement

Recommended Python Training
Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now
Filed Under: Dictionary
Author: PFB Staff Writer

More Python Topics
API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Errorhandling Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

The dict “dictionary” type is very important because it takes in disorganized data, organizes it, and it is fast. The dict here is based on the “hash table” data structure. You will learn how to build and analyze a hash table in CS106B, here we’re happy to just use them. Many important algorithms leverage hash tables in some way since they can handle large data sets and remain fast. ‘dict’ is the name of the Python dict type, so we’ll use just ‘d’ as a generic variable name.

d = {} # Create empty dict
d[‘ca’] = ‘California’ # 1. Set key/value pairs into dict
d[‘ok’] = ‘Oklahoma’
d[‘nj’] = ‘New Jersey’
d[‘tx’] = ‘Texas’
val = d[‘nj’] # 2. Retrieve value by key
val = d[‘xx’] # fails with KeyError
check = ‘nj’ in d # 3. in check -> True

dict with keys ca ok nj tx
1. d[‘ca’] = ‘California’ – with equal-sign: d[key] = xxx creates a key/value pair in the dict. If a pair was in there already, it is overwritten.

2. val = d[‘nj’] – referring to d[key] retrieves the value for that key, or is a KeyError. Code needs to check that the key is in before doing [ ] retrieval.

3. if ‘nj’ in d: – use in to check if a key is in the dict or not. This sort of ‘in’ works for lists too, but for dicts it’s much faster.

Key point: dicts (hash tables) are fast. Even if the dict has 1 million key/value pairs in it, performing the get/set/in of single key is very fast. If the dict grows to hold 10 million key/value pairs, the speed is largely unchanged.

Strategy: therefore if we are reading a file or a network taking in disorganized data, load the data into a dict choosing the key and value definitions we want to output. The data will become organized by that key, even though it was in random order as it was read.

The type used as key should be “immutable”, often a string or int (or tuple when we get to those).

Dict Counting
Here is the canonical logic to load up a dict – in this example the code counts the number of occurrences of each word, but many useful dict operations will follow this basic loop/in/out pattern.

def strs_counts(strs):
“””
Given a list of strings, return a ‘counts’ dict of
str->count key/value pairs
“””
counts = {}
for s in strs:
# fix up not-in case
if not s in counts:
counts[s] = 0
# invariant: at this line, s is in
counts[s] += 1
# alternate ‘else’ solution:
#if not s in counts:
# counts[s] = 1
#else:
# counts[s] += 1
return counts
Getting Data out of Dict
1. len(d) – as you would guess, the number of key/value pairs in the dict

2. d.get(key) – retrieves the value for a key, but if the key is not there, returns None by default (vs. throwing an error like [ ]). A 2 parameter form d.get(key, missing-value) specifies what value to return if the key is missing. This forms an alternative to writing if/in logic to check if the key is in.

3. d.keys() – returns an iterable of all the keys in dict (in a random order). Can loop over this to get each key. The keys alone, no values.

4. d.values() – returns an iterable of all the values in dict (in a random order). Can loop over this to get each value.

5. d.items() returns an iterable of the key,value pairs. This works with a particular sort of double-variable loop, see below. If you want to look at all of the key,value pairs, this is the most direct way.

The most common pattern for looping over a dict, using sorted() function which returns a linear collection sorted into increasing order:

def print_counts2(counts):
# sort the keys for nicer output
for key in sorted(counts.keys()):
print(key, counts[key])
The double-variable key,value loop (more detailed explanation in the tuples section below)
def print_counts3(counts):
# key,value loop over .items()
# unsorted
for key,value in counts.items():
print(key, value)
Tuples and Dicts
One handy use of tuples is the dict.items() function, which returns the entire contents of the dict as an list of len-2 (key, value) tuples.

>>> d = {‘a’:1, ‘d’:4, ‘c’:2, ‘b’:3}
>>> d
{‘a’: 1, ‘d’: 4, ‘c’: 2, ‘b’: 3}
>>> d.items()
dict_items([(‘a’, 1), (‘d’, 4), (‘c’, 2), (‘b’, 3)]) # (key, value) tuples
>>> sorted(d.items()) # same tuples, sorted by key
[(‘a’, 1), (‘b’, 3), (‘c’, 2), (‘d’, 4)]
Sorting of tuples goes left-to-right within each tuple — first sorting by all the [0] values across the tuples, then by [1], and so on.

Once all the data has been loaded into a dict, it’s natural to have a process-all-the-data phase. This can be written as a loop over the above d.items() list. The loop syntax below takes one tuple off the list for each iteration, setting the two variable, key and value each time:

# Example: for loop setting key/value for each iteration
for key,value in d.items():
# use key and value in here
This is a special version of the for loop, where there are multiple variables, and the number of variables matches the size of a tuples coming off the list. The above example, looping key,value over dict.items() is probably the most common use of this multiple-variable variant of the for loop.

Python’s efficient key/value hash table structure is called a “dict”. The contents of a dict can be written as a series of key:value pairs within braces { }, e.g. dict = {key1:value1, key2:value2, … }. The “empty dict” is just an empty pair of curly braces {}.

Looking up or setting a value in a dict uses square brackets, e.g. dict[‘foo’] looks up the value under the key ‘foo’. Strings, numbers, and tuples work as keys, and any type can be a value. Other types may or may not work correctly as keys (strings and tuples work cleanly since they are immutable). Looking up a value which is not in the dict throws a KeyError — use “in” to check if the key is in the dict, or use dict.get(key) which returns the value or None if the key is not present (or get(key, not-found) allows you to specify what value to return in the not-found case).

## Can build up a dict by starting with the the empty dict {}
## and storing key/value pairs into the dict like this:
## dict[key] = value-for-that-key
dict = {}
dict[‘a’] = ‘alpha’
dict[‘g’] = ‘gamma’
dict[‘o’] = ‘omega’

print dict ## {‘a’: ‘alpha’, ‘o’: ‘omega’, ‘g’: ‘gamma’}

print dict[‘a’] ## Simple lookup, returns ‘alpha’
dict[‘a’] = 6 ## Put new key/value into dict
‘a’ in dict ## True
## print dict[‘z’] ## Throws KeyError
if ‘z’ in dict: print dict[‘z’] ## Avoid KeyError
print dict.get(‘z’) ## None (instead of KeyError)
dict with keys ‘a’ ‘o’ ‘g’

A for loop on a dictionary iterates over its keys by default. The keys will appear in an arbitrary order. The methods dict.keys() and dict.values() return lists of the keys or values explicitly. There’s also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary. All of these lists can be passed to the sorted() function.

## By default, iterating over a dict iterates over its keys.
## Note that the keys are in a random order.
for key in dict: print key
## prints a g o

## Exactly the same as above
for key in dict.keys(): print key

## Get the .keys() list:
print dict.keys() ## [‘a’, ‘o’, ‘g’]

## Likewise, there’s a .values() list of values
print dict.values() ## [‘alpha’, ‘omega’, ‘gamma’]

## Common case — loop over the keys in sorted order,
## accessing each key/value
for key in sorted(dict.keys()):
print key, dict[key]

## .items() is the dict expressed as (key, value) tuples
print dict.items() ## [(‘a’, ‘alpha’), (‘o’, ‘omega’), (‘g’, ‘gamma’)]

## This loop syntax accesses the whole dict by looping
## over the .items() tuple list, accessing one (key, value)
## pair on each iteration.
for k, v in dict.items(): print k, ‘>’, v
## a > alpha o > omega g > gamma
There are “iter” variants of these methods called iterkeys(), itervalues() and iteritems() which avoid the cost of constructing the whole list — a performance win if the data is huge. However, I generally prefer the plain keys() and values() methods with their sensible names. In Python 3 revision, the need for the iterkeys() variants is going away.

Strategy note: from a performance point of view, the dictionary is one of your greatest tools, and you should use it where you can as an easy way to organize data. For example, you might read a log file where each line begins with an IP address, and store the data into a dict using the IP address as the key, and the list of lines where it appears as the value. Once you’ve read in the whole file, you can look up any IP address and instantly see its list of lines. The dictionary takes in scattered data and makes it into something coherent.

Dict Formatting
The % operator works conveniently to substitute values from a dict into a string by name:

hash = {}
hash[‘word’] = ‘garfield’
hash[‘count’] = 42
s = ‘I want %(count)d copies of %(word)s’ % hash # %d for int, %s for string
# ‘I want 42 copies of garfield’
Del
The “del” operator does deletions. In the simplest case, it can remove the definition of a variable, as if that variable had not been defined. Del can also be used on list elements or slices to delete that part of the list and to delete entries from a dictionary.

var = 6
del var # var no more!

list = [‘a’, ‘b’, ‘c’, ‘d’]
del list[0] ## Delete first element
del list[-2:] ## Delete last two elements
print list ## [‘b’]

dict = {‘a’:1, ‘b’:2, ‘c’:3}
del dict[‘b’] ## Delete ‘b’ entry
print dict ## {‘a’:1, ‘c’:3}

Leave a Reply

Your email address will not be published. Required fields are marked *