EzDevInfo.com

dictionary interview questions

Top dictionary frequently asked interview questions

Sort a Python dictionary by value

I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.

I can sort on the keys, but how can I sort based on the values?

Note: I have read Stack Overflow question How do I sort a list of dictionaries by values of the dictionary in Python? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.


Source: (StackOverflow)

How can I merge two Python dictionaries in a single expression?

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of modifying a dict in-place.

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}

How can I get that final merged dict in z, not x?

(To be extra-clear, the last-one-wins conflict-handling of dict.update() is what I'm looking for as well.)


Source: (StackOverflow)

Advertisements

How can I Initialize a static Map?

How would you initialise a static Map in Java?

Method one: Static initializer
Method two: instance initialiser (anonymous subclass) or some other method?

What are the pros and cons of each?

Here is an example illustrating two methods:

import java.util.HashMap;
import java.util.Map;

public class Test {
    private static final Map<Integer, String> myMap = new HashMap<Integer, String>();
    static {
        myMap.put(1, "one");
        myMap.put(2, "two");
    }

    private static final Map<Integer, String> myMap2 = new HashMap<Integer, String>(){
        {
            put(1, "one");
            put(2, "two");
        }
    };
}

Source: (StackOverflow)

Iterating over dictionaries using for loops in Python

I am a bit puzzled by the following code:

d = {'x': 1, 'y': 2, 'z': 3} 
for key in d:
    print key, 'corresponds to', d[key]

What I don't understand is the key portion. How does Python recognize that it needs only to read the key from the dictionary? Is key a special word in Python? Or is it simply a variable?


Source: (StackOverflow)

Python List Comprehension Vs. Map

Is there a reason to prefer using map() over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other?


Source: (StackOverflow)

How can I sort a dictionary by key?

What would be a nice way to go from {2:3, 1:89, 4:5, 3:0} to {1:89, 2:3, 3:0, 4:5}?
I checked some posts but they all use the "sorted" operator that returns tuples.


Source: (StackOverflow)

How to efficiently iterate over each Entry in a Map?

If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?

Will the ordering of elements depend on the specific map implementation that I have for the interface?


Source: (StackOverflow)

Delete an element from a dictionary

Is there a way to delete an element from a dictionary in Python?

I know I can just call .pop on the dictionary, but that returns the element that was removed. What I'm looking for is something returns the dictionary minus the element in question.

At present I have a helper function that accepts the dictionary in question as parameter, and then returns a dictionary with the element removed, Is there a more elegant solution?


Source: (StackOverflow)

Convert Python dict to object?

I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.

For example:

>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}

Should be accessible in this way:

>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar

I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?

Thank you in advance.


Source: (StackOverflow)

Getting key with maximum value in dictionary?

I have a dictionary: keys are strings, values are integers.

Example:

stats = {'a':1000, 'b':3000, 'c': 100}

I'd like to get 'b' as an answer, since it's the key with a higher value.

I did the following, using an intermediate list with reversed key-value tuples:

inverse = [(value, key) for key, value in stats.items()]
print max(inverse)[1]

Is that one the better (or even more elegant) approach?


Source: (StackOverflow)

Difference between map and collect in Ruby?

I have Googled this and got patchy / contradictory opinions - is there actually any difference between doing a map and doing a collect on an array in Ruby/Rails?

The docs don't seem to suggest any, but are there perhaps differences in method or performance?


Source: (StackOverflow)

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

For example I have two dicts:

Dict A: {'a':1, 'b':2, 'c':3}
Dict B: {'b':3, 'c':4, 'd':5}

I need a pythonic way of 'combining' two dicts such that the result is :

{'a':1, 'b':5, 'c':7, 'd':5}

That is to say: if a key appears in both dicts, add their values, if it appears in only one dict, keep its value.


Source: (StackOverflow)

Create a dictionary with list comprehension in Python

I like the Python list comprehension syntax.

Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

mydict = {(k,v) for (k,v) in blah blah blah}  # doesn't work :(

Source: (StackOverflow)

How do I sort a list of dictionaries by values of the dictionary in Python?

I got a list of dictionaries and want that to be sorted by a value of that dictionary.

This

[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]

sorted by name, should become

[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]

Source: (StackOverflow)

How do you sort a dictionary by value?

I often have to sort a dictionary, consisting of keys & values, by value. For example, I have a hash of words and respective frequencies, that I want to order by frequency.

There is a SortedList which is good for a single value (say frequency), that I want to map it back to the word.

SortedDictionary orders by key, not value. Some resort to a custom class, but is there a cleaner way?


Source: (StackOverflow)