How can I make a dictionary from separate lists of keys and values?

I want to combine these:

keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']

Into a single dictionary:

{'name': 'Monty', 'age': 42, 'food': 'spam'}


Asked by: William591 | Posted: 24-09-2021






Answer 1

Like this:

keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) # {'a': 1, 'b': 2, 'c': 3}

Voila :-) The pairwise dict constructor and zip function are awesomely useful.

Answered by: Emily639 | Posted: 25-10-2021



Answer 2

Imagine that you have:

keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')

What is the simplest way to produce the following dictionary ?

dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}

Most performant, dict constructor with zip

new_dict = dict(zip(keys, values))

In Python 3, zip now returns a lazy iterator, and this is now the most performant approach.

dict(zip(keys, values)) does require the one-time global lookup each for dict and zip, but it doesn't form any unnecessary intermediate data-structures or have to deal with local lookups in function application.

Runner-up, dict comprehension:

A close runner-up to using the dict constructor is to use the native syntax of a dict comprehension (not a list comprehension, as others have mistakenly put it):

new_dict = {k: v for k, v in zip(keys, values)}

Choose this when you need to map or filter based on the keys or value.

In Python 2, zip returns a list, to avoid creating an unnecessary list, use izip instead (aliased to zip can reduce code changes when you move to Python 3).

from itertools import izip as zip

So that is still (2.7):

new_dict = {k: v for k, v in zip(keys, values)}

Python 2, ideal for <= 2.6

izip from itertools becomes zip in Python 3. izip is better than zip for Python 2 (because it avoids the unnecessary list creation), and ideal for 2.6 or below:

from itertools import izip
new_dict = dict(izip(keys, values))

Result for all cases:

In all cases:

>>> new_dict
{'age': 42, 'name': 'Monty', 'food': 'spam'}

Explanation:

If we look at the help on dict we see that it takes a variety of forms of arguments:


>>> help(dict)

class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)

The optimal approach is to use an iterable while avoiding creating unnecessary data structures. In Python 2, zip creates an unnecessary list:

>>> zip(keys, values)
[('name', 'Monty'), ('age', 42), ('food', 'spam')]

In Python 3, the equivalent would be:

>>> list(zip(keys, values))
[('name', 'Monty'), ('age', 42), ('food', 'spam')]

and Python 3's zip merely creates an iterable object:

>>> zip(keys, values)
<zip object at 0x7f0e2ad029c8>

Since we want to avoid creating unnecessary data structures, we usually want to avoid Python 2's zip (since it creates an unnecessary list).

Less performant alternatives:

This is a generator expression being passed to the dict constructor:

generator_expression = ((k, v) for k, v in zip(keys, values))
dict(generator_expression)

or equivalently:

dict((k, v) for k, v in zip(keys, values))

And this is a list comprehension being passed to the dict constructor:

dict([(k, v) for k, v in zip(keys, values)])

In the first two cases, an extra layer of non-operative (thus unnecessary) computation is placed over the zip iterable, and in the case of the list comprehension, an extra list is unnecessarily created. I would expect all of them to be less performant, and certainly not more-so.

Performance review:

In 64 bit Python 3.8.2 provided by Nix, on Ubuntu 16.04, ordered from fastest to slowest:

>>> min(timeit.repeat(lambda: dict(zip(keys, values))))
0.6695233230129816
>>> min(timeit.repeat(lambda: {k: v for k, v in zip(keys, values)}))
0.6941362579818815
>>> min(timeit.repeat(lambda: {keys[i]: values[i] for i in range(len(keys))}))
0.8782548159942962
>>> 
>>> min(timeit.repeat(lambda: dict([(k, v) for k, v in zip(keys, values)])))
1.077607496001292
>>> min(timeit.repeat(lambda: dict((k, v) for k, v in zip(keys, values))))
1.1840861019445583

dict(zip(keys, values)) wins even with small sets of keys and values, but for larger sets, the differences in performance will become greater.

A commenter said:

min seems like a bad way to compare performance. Surely mean and/or max would be much more useful indicators for real usage.

We use min because these algorithms are deterministic. We want to know the performance of the algorithms under the best conditions possible.

If the operating system hangs for any reason, it has nothing to do with what we're trying to compare, so we need to exclude those kinds of results from our analysis.

If we used mean, those kinds of events would skew our results greatly, and if we used max we will only get the most extreme result - the one most likely affected by such an event.

A commenter also says:

In python 3.6.8, using mean values, the dict comprehension is indeed still faster, by about 30% for these small lists. For larger lists (10k random numbers), the dict call is about 10% faster.

I presume we mean dict(zip(... with 10k random numbers. That does sound like a fairly unusual use case. It does makes sense that the most direct calls would dominate in large datasets, and I wouldn't be surprised if OS hangs are dominating given how long it would take to run that test, further skewing your numbers. And if you use mean or max I would consider your results meaningless.

Let's use a more realistic size on our top examples:

import numpy
import timeit
l1 = list(numpy.random.random(100))
l2 = list(numpy.random.random(100))

And we see here that dict(zip(... does indeed run faster for larger datasets by about 20%.

>>> min(timeit.repeat(lambda: {k: v for k, v in zip(l1, l2)}))
9.698965263989521
>>> min(timeit.repeat(lambda: dict(zip(l1, l2))))
7.9965161079890095

Answered by: Sydney231 | Posted: 25-10-2021



Answer 3

Try this:

>>> import itertools
>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> adict = dict(itertools.izip(keys,values))
>>> adict
{'food': 'spam', 'age': 42, 'name': 'Monty'}

In Python 2, it's also more economical in memory consumption compared to zip.

Answered by: Stella872 | Posted: 25-10-2021



Answer 4

keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
out = dict(zip(keys, values))

Output:

{'food': 'spam', 'age': 42, 'name': 'Monty'}

Answered by: Julian530 | Posted: 25-10-2021



Answer 5

You can also use dictionary comprehensions in Python ≥ 2.7:

>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> {k: v for k, v in zip(keys, values)}
{'food': 'spam', 'age': 42, 'name': 'Monty'}

Answered by: Owen492 | Posted: 25-10-2021



Answer 6

A more natural way is to use dictionary comprehension

keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')    
dict = {keys[i]: values[i] for i in range(len(keys))}

Answered by: Catherine155 | Posted: 25-10-2021



Answer 7

If you need to transform keys or values before creating a dictionary then a generator expression could be used. Example:

>>> adict = dict((str(k), v) for k, v in zip(['a', 1, 'b'], [2, 'c', 3])) 

Take a look Code Like a Pythonista: Idiomatic Python.

Answered by: William647 | Posted: 25-10-2021



Answer 8

with Python 3.x, goes for dict comprehensions

keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')

dic = {k:v for k,v in zip(keys, values)}

print(dic)

More on dict comprehensions here, an example is there:

>>> print {i : chr(65+i) for i in range(4)}
    {0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'}

Answered by: Maya211 | Posted: 25-10-2021



Answer 9

For those who need simple code and aren’t familiar with zip:

List1 = ['This', 'is', 'a', 'list']
List2 = ['Put', 'this', 'into', 'dictionary']

This can be done by one line of code:

d = {List1[n]: List2[n] for n in range(len(List1))}

Answered by: Dainton596 | Posted: 25-10-2021



Answer 10

you can use this below code:

dict(zip(['name', 'age', 'food'], ['Monty', 42, 'spam']))

But make sure that length of the lists will be same.if length is not same.then zip function turncate the longer one.

Answered by: Thomas287 | Posted: 25-10-2021



Answer 11

  • 2018-04-18

The best solution is still:

In [92]: keys = ('name', 'age', 'food')
...: values = ('Monty', 42, 'spam')
...: 

In [93]: dt = dict(zip(keys, values))
In [94]: dt
Out[94]: {'age': 42, 'food': 'spam', 'name': 'Monty'}

Tranpose it:

    lst = [('name', 'Monty'), ('age', 42), ('food', 'spam')]
    keys, values = zip(*lst)
    In [101]: keys
    Out[101]: ('name', 'age', 'food')
    In [102]: values
    Out[102]: ('Monty', 42, 'spam')

Answered by: Kellan219 | Posted: 25-10-2021



Answer 12

Here is also an example of adding a list value in you dictionary

list1 = ["Name", "Surname", "Age"]
list2 = [["Cyd", "JEDD", "JESS"], ["DEY", "AUDIJE", "PONGARON"], [21, 32, 47]]
dic = dict(zip(list1, list2))
print(dic)

always make sure the your "Key"(list1) is always in the first parameter.

{'Name': ['Cyd', 'JEDD', 'JESS'], 'Surname': ['DEY', 'AUDIJE', 'PONGARON'], 'Age': [21, 32, 47]}

Answered by: Fiona266 | Posted: 25-10-2021



Answer 13

I had this doubt while I was trying to solve a graph-related problem. The issue I had was I needed to define an empty adjacency list and wanted to initialize all the nodes with an empty list, that's when I thought how about I check if it is fast enough, I mean if it will be worth doing a zip operation rather than simple assignment key-value pair. After all most of the times, the time factor is an important ice breaker. So I performed timeit operation for both approaches.

import timeit
def dictionary_creation(n_nodes):
    dummy_dict = dict()
    for node in range(n_nodes):
        dummy_dict[node] = []
    return dummy_dict


def dictionary_creation_1(n_nodes):
    keys = list(range(n_nodes))
    values = [[] for i in range(n_nodes)]
    graph = dict(zip(keys, values))
    return graph


def wrapper(func, *args, **kwargs):
    def wrapped():
        return func(*args, **kwargs)
    return wrapped

iteration = wrapper(dictionary_creation, n_nodes)
shorthand = wrapper(dictionary_creation_1, n_nodes)

for trail in range(1, 8):
    print(f'Itertion: {timeit.timeit(iteration, number=trails)}\nShorthand: {timeit.timeit(shorthand, number=trails)}')

For n_nodes = 10,000,000 I get,

Iteration: 2.825081646999024 Shorthand: 3.535717916001886

Iteration: 5.051560923002398 Shorthand: 6.255070794999483

Iteration: 6.52859034499852 Shorthand: 8.221581164998497

Iteration: 8.683652416999394 Shorthand: 12.599181543999293

Iteration: 11.587241565001023 Shorthand: 15.27298851100204

Iteration: 14.816342867001367 Shorthand: 17.162912737003353

Iteration: 16.645022411001264 Shorthand: 19.976680120998935

You can clearly see after a certain point, iteration approach at n_th step overtakes the time taken by shorthand approach at n-1_th step.

Answered by: Dainton379 | Posted: 25-10-2021



Answer 14

keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
dic = {}
c = 0
for i in keys:
    dic[i] = values[c]
    c += 1

print(dic)
{'name': 'Monty', 'age': 42, 'food': 'spam'}

Answered by: Thomas409 | Posted: 25-10-2021



Answer 15

It can be done by the following way.

keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam'] 

dict = {}

for i in range(len(keys)):
    dict[keys[i]] = values[i]
    
print(dict)

{'name': 'Monty', 'age': 42, 'food': 'spam'}

Answered by: Thomas554 | Posted: 25-10-2021



Answer 16

Solution as dictionary comprehension with enumerate:

dict = {item : values[index] for index, item in enumerate(keys)}

Solution as for loop with enumerate:

dict = {}
for index, item in enumerate(keys):
    dict[item] = values[index]

Answered by: Aida163 | Posted: 25-10-2021



Answer 17

If you are working with more than 1 set of values and wish to have a list of dicts you can use this:

def as_dict_list(data: list, columns: list):
    return [dict((zip(columns, row))) for row in data]

Real-life example would be a list of tuples from a db query paired to a tuple of columns from the same query. Other answers only provided for 1 to 1.

Answered by: John585 | Posted: 25-10-2021



Answer 18

method without zip function

l1 = [1,2,3,4,5]
l2 = ['a','b','c','d','e']
d1 = {}
for l1_ in l1:
    for l2_ in l2:
        d1[l1_] = l2_
        l2.remove(l2_)
        break  

print (d1)


{1: 'd', 2: 'b', 3: 'e', 4: 'a', 5: 'c'}

Answered by: Sydney997 | Posted: 25-10-2021



Answer 19

Although there are multiple ways of doing this but i think most fundamental way of approaching it; creating a loop and dictionary and store values into that dictionary. In the recursive approach the idea is still same it but instead of using a loop, the function called itself until it reaches to the end. Of course there are other approaches like using dict(zip(key, value)) and etc. These aren't the most effective solutions.

y = [1,2,3,4]
x = ["a","b","c","d"]

# This below is a brute force method
obj = {}
for i in range(len(y)):
    obj[y[i]] = x[i]
print(obj)

# Recursive approach 
obj = {}
def map_two_lists(a,b,j=0):
    if j < len(a):
        obj[b[j]] = a[j]
        j +=1
        map_two_lists(a, b, j)
        return obj
      


res = map_two_lists(x,y)
print(res)

Both the results should print

{1: 'a', 2: 'b', 3: 'c', 4: 'd'}  

Answered by: Elise841 | Posted: 25-10-2021



Similar questions

python - Write key to separate csv based on value in dictionary

[Using Python3] I have a csv file that has two columns (an email address and a country code; script is made to actually make it two columns if not the case in the original file - kind of) that I want to split out by the value in the second column and output in separate csv files. eppetj@desrfpkwpwmhdc.com us ==&gt; output-us.csv uheuyvhy@zyetccm.com de ==&gt; output-de.csv avpxhb...


python - Dictionary of lists or separate lists?

Closed. This question needs to be more focused. It ...


python - Dictionary keys and values to separate numpy arrays

I have a dictionary as Samples = {5.207403005022627: 0.69973543384229719, 6.8970222167794759: 0.080782939731898179, 7.8338517407140973: 0.10308033284258854, 8.5301143255505334: 0.018640838362318335, 10.418899728838058: 0.14427355015329846, 5.3983946820220501: 0.51319796560976771} I want to separate the keys and values into 2 numpy arrays. I tried


python - split values in dictionary in separate values

I have this type of string: sheet = """ magenta turquoise,PF00575 tan,PF00154,PF06745,PF08423,PF13481,PF14520 turquoise, PF00011 NULL """ Every line starts with an identifier (e.g. tan, magenta...) What I want is to count the number of occurrences of each PF-number per identifier. So, the final structure would be something like this: magenta turquoise tan...


python - How to separate a list into dictionary based on first and second values

This question already has answers here:


Python adding dictionary values from separate script runs

I have a dictionary I generated within a script: dict1 = {'a': 1, 'b': 2, 'c':3} The script to generate the dictionary will be run many times over different files to generate more dictionaries, each within their own script: dict2 = {'a': 5, 'b': 3, 'c':2} dict3 = {'a': 2, 'b': 1, 'c':0} My plan was to add these to a file individually, then add values with ...


How to get all keys that have the same name and put them in a separate dictionary in Python

Closed. This question needs to be more focused. It ...


python - How to assign values from a list to a dictionary and back into a separate list?

I am trying to make a loop that can roll my dice and assign the rolled value into a list that can then be put through a dictionary to get back the values written in the dictionary. My dictionary is as follows: scores = {1:1000, 2:200, 3:300, 4:400, 5:500, 6:600} rolls = [] for i in range(5): self.rolls.append(random.randint(1,6)) my_score = 0 How do I make the values in rolls that of t...


python - How to match dictionary value list items stored to items in a separate list?

I am trying to match list items to items in dictionary value which are stored as a list. I have the following list: new_list = ['apple', 'banana', 'orange'] and the following dictionary: new_dict = {abc: ['apple', 'kiwi'], bca: ['strawberry', 'banana', 'mango'], dcf: ['watermelon', 'apple', 'starfruit']} What I want to do is match items in new_list...


python - How to separate values in a dictionary to be put into CSV?

This question already has answers here:


python - how to split dictionary to separate rows in pandas

I have a dataframe like this: | col1 | d ------------------------------------------- 0 | A | {'student99': [[0.83, "nice"]]} 1 | B | {'student99': [[0.84, "great"], [0.89, "cool"]]} 2 | C | {'student98': [[0.85, "amazing"]], 'student97': [[0.9, "crazy"]]} And I'm trying to convert to a dataframe like: | col1 | student | grade | comment -----------------------...


python - How to separate a dictionary into list based on the keys?

I have dictionary with a fixed format like: dict = {1111: {'vehicle_id': 1111, 'vehicle_capacity': 800}, 3333: {'vehicle_id': 3333, 'vehicle_capacity': 4800}} The output I would like to get is: list_dict1 = [{1111: {'vehicle_id': 1111, 'vehicle_capacity': 800}] list_dict2 = [{3333: {'vehicle_id': 3333, 'vehicle_capacity': 4800}] The format of dic...


python - How to separate the dictionary with split values

Dictionary is below a = {'querystring': {'dataproduct.keyword': 'abc,def'}} How to split into two dictionary with values? a['querystring'] = {'dataproduct.keyword': 'abc,def'} Expected out while printing {'dataproduct.keyword': 'abc'} {'dataproduct.keyword': 'def'} Since dictionary is hashmap [{'dataproduct.keyword': 'abc'} {'...


python - plot separate plots using dictionary of lists

What I want is to generate different plots using one dictionary of lists (each key one list). I accumulate the values and at the moment to plot each list, they are going all to the same plot and the last plot looks like as in the figure. Can you tell me some ideas about how to solve it? for k, v in dict_btw_longmers.items(): print(k) out_fig = k + &quot;cumulative.pdf&quot;...


python - How do I merge 2 separate key value pairs inside the same dictionary?

I have one dictionary with 2 separate key-value pairs and I want to merge them into 1 list with separate dictionaries for all key-value pairs. Example Input: {'Boys': [72, 68, 70, 69, 74], 'Girls': [63, 65, 69, 62, 61]} Example Output: [{'Boys': 72,'Girls': 63}, {'Boys': 68, 'Girls': 65}, {'Boys': 70, 'Girls': 69}, {'Boys': 69, 'Girls': 62}, {‘Boys’:74,'‘Girls':61] ...


python - How to separate values from pandas series into dictionary?

I have a pandas series like this: LIST 0 ITEM1 1 Element1 2 Element2 3 Element3 4 Element4 5 Element5 6 Element6 7 Element7 8 ITEM2 9 Element8 10 ELEMENT9 11 ELEMENT10 12 Element11 13 Element12 14 Element13 15 Element14 16 Element2 17 ...


python - How to separate dictionary in data frame each in one column and only keep the value without the key

I have a data frame contains columns of dictionaries has few items inside it, i wanat seperate each value in one column and keep only the value. right now like this dic {'_id': '1', 'value': 'apple'} {'_id': '2', 'value': 'car'} I want them to be...


python - How do I separate dictionary values in Pandas?

My dataframe 'json' contains a column with dictionary values. I want to be able to strip the dictionary of the key 'display name', so i just end up with the values of the location. How do I do this?


python - how to separate a dictionary item from a nested list

I am stuck in a project where I have to seperate all Dictionary item from a list and create a dataframe from that. Below is the json file link. Link:- https://drive.google.com/file/d/1H76rjDEZweVGzPcziT5Z6zXqzOSmVZQd/view?usp=sharing I had written this code which coverting the all list it...


python - How to Split a Dictionary Value into 2 Separate Key Values

I currently have a dictionary where the values are: disney_data = { 'title': ['Gus (1976)', 'Johnny Kapahala: Back on Board (2007)', 'The Adventures of Huck Finn (1993)', 'The Simpsons (1989)', 'Atlantis: Milo’s Return (2003)'] } I would like to split up the title from the year value and have a dictionary like: new_disney_data = { 'title' : ['Gus', ...


python - Replace dictionary value in a separate file

I'm on python 2.7.3. I wrote a simple code that searches through dictionary keys, and when it finds the key defined by var_par, it iteratively substitutes new values for it from a list array: var_par = 'B' array = [1.4, 2.6, 4.8, 3.56] params = { "A": ["A part of", "#comment 1"], "B": [1.2, "#comment 2"], "C": ["the test run.", "#comment 3"]...


python - Is there a better way to store a twoway dictionary than storing its inverse separate?

This question already has answers here:


python - Write key to separate csv based on value in dictionary

[Using Python3] I have a csv file that has two columns (an email address and a country code; script is made to actually make it two columns if not the case in the original file - kind of) that I want to split out by the value in the second column and output in separate csv files. eppetj@desrfpkwpwmhdc.com us ==&gt; output-us.csv uheuyvhy@zyetccm.com de ==&gt; output-de.csv avpxhb...


dictionary - Python: tuple values into separate df columns?

Following is the output of my dictionary output: {'20140201':(2.8,a),'20140202':(3.4,b),'20140203':(5.4,c)} I want to convert this dictionary output to a dataframe containing three columns, lets call it 'x','y','z'. Column x should have datevalues, y should have numerical value of tuple and z should have class value of the tuple. Is there any good way to do so. I know I can take individual...


python - Dictionary of lists or separate lists?

Closed. This question needs to be more focused. It ...


python - Dictionary keys and values to separate numpy arrays

I have a dictionary as Samples = {5.207403005022627: 0.69973543384229719, 6.8970222167794759: 0.080782939731898179, 7.8338517407140973: 0.10308033284258854, 8.5301143255505334: 0.018640838362318335, 10.418899728838058: 0.14427355015329846, 5.3983946820220501: 0.51319796560976771} I want to separate the keys and values into 2 numpy arrays. I tried


python return dictionary in separate lines in __repr__ method

I'm need to return my dictionary generated in the class using repr method, and i want it to return in separate lines. Is there any way i can do it? def __repr__: return str(self.maze) expected: { (0, 0):[(0, 1), (1, 0)] (0, 1):[(0, 0), (1, 1)] (1, 0):[(0, 0), (1, 1)] (1, 1):[(0, 1), (1, 0)] } what i got: {(0, 1)...


python - write values of dictionary in separate csv columns and create headers

I have created a dictionary that uses date as the key and added multiple values to each date. The dictionary is populated by reading an original csv so that I can create totals per date. My Code: import csv ##Opens the csv file to be read tradedata=open("test.csv","r") ##Reads the csv file tradedatareader = csv.reader(tradedata,delimiter=',',quotechar='"') ##create dictionary my_dict = {} for row...


python - split values in dictionary in separate values

I have this type of string: sheet = """ magenta turquoise,PF00575 tan,PF00154,PF06745,PF08423,PF13481,PF14520 turquoise, PF00011 NULL """ Every line starts with an identifier (e.g. tan, magenta...) What I want is to count the number of occurrences of each PF-number per identifier. So, the final structure would be something like this: magenta turquoise tan...


python - How to separate a list into dictionary based on first and second values

This question already has answers here:


sorting - In Python, how can you easily retrieve sorted items from a dictionary?

Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key? For example, you had this: d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}


Python dictionary from an object's fields

Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: &gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } NOTE: It should not include methods. Only fields.


python - How do you retrieve items from a dictionary in the order that they're inserted?

Is it possible to retrieve items from a Python dictionary in the order that they were inserted?


python - Dictionary or If statements, Jython

I am writing a script at the moment that will grab certain information from HTML using dom4j. Since Python/Jython does not have a native switch statement I decided to use a whole bunch of if statements that call the appropriate method, like below: if type == 'extractTitle': extractTitle(dom) if type == 'extractMetaTags': extractMetaTags(dom)


Is a Python dictionary an example of a hash table?

One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?


python - Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?

The list sort() method is a modifier function that returns None. So if I want to iterate through all of the keys in a dictionary I cannot do: for k in somedictionary.keys().sort(): dosomething() Instead, I must: keys = somedictionary.keys() keys.sort() for k in keys: dosomething() Is there a pretty way to iterate t...


python - Interface to versioned dictionary

I have an versioned document store which I want to access through an dict like interface. Common usage is to access the latest revision (get, set, del), but one should be able to access specific revisions too (keys are always str/unicode or int). from UserDict import DictMixin class VDict(DictMixin): def __getitem__(self, key): if isinstance(key, tuple): docid, rev = key e...


python - List all words in a dictionary that start with <user input>

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! Edit: I'm using python, but I assume that this is a fairly language-independent problem.


python - Check if a given key already exists in a dictionary and increment it

How do I find out if a key in a dictionary has already been set to a non-None value? I want to increment the value if there's already one there, or set it to 1 otherwise: my_dict = {} if my_dict[key] is not None: my_dict[key] = 1 else: my_dict[key] += 1


Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?

I have a list of variable names, like this: ['foo', 'bar', 'baz'] (I originally asked how I convert a list of variables. See Greg Hewgill's answer below.) How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values of the variables? {'foo': foo, 'bar': bar, 'baz': baz} Now that I'm re-aski...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top