Dictionaries in Python

I am trying to speed up the use of dictionaries. I spent three hours last night searching the Internet for examples that looked like some of the things I'm trying to do. For example, suppose I have two dictionaries (in fact, I have two lists of dictionaries).

d1={key1:1, key2:2}
d2={key1:1, key2:'A', key4:4}

I want to update d1 so that it looks like this:

d1={key1:1, key2:[2,'A'], key3:3, key4:4}

I cannot find suitable examples to start me. I have many books and I also looked through them, but they all seem to have similar examples that I find on the Internet.

Does anyone know a place or book with clear examples and descriptions of the use of dictionaries?

I think one of the problems that I am facing is that I do not understand how links are supported when I access the dictionary.

I can check if two dictionaries have a common key:

for k in d1.keys():
    for k2 in d2.keys():
        if k==k2:
            print 'true'

, .

, .

+5
9

iPython (easy_install ipython), , ? dir:

In [2]: dir {}
------> dir({})

Out[2]: 
['__class__',
 ...
 'keys',
 'pop',
 'popitem',
 'setdefault',
 'update',
 'values']

In [3]: {}.update?
Type:       dict
Base Class: <type 'dict'>
String Form:    {}
Namespace:  Interactive
Length:     0
Docstring:
    dict() -> new empty dictionary.
    dict(mapping) -> new dictionary initialized from a mapping object's
        (key, value) pairs.
    dict(seq) -> new dictionary initialized as if via:
        d = {}
        for k, v in seq:
            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)

(,)

, , : , (, set?), :

common_keys = [k for k in dict1 if k in dict2]

(.. " k dict1, dict2" ) ( , O (1), O (| dict1 |))

edit: , dicts ... Lott , setdefault :

new = {}
for (k, v) in dict1.items():
    new.setdefault(k, []).append(v)
for (k, v) in dict2.items():
    new.setdefault(k, []).append(v)
+6

:

import collections
merged = collections.defaultdict(list)
for k in d1:
   merged[k].append( d1[k] )
for k in d2:
   merged[k].append( d2[k] )

, .

, , .

import collections
merged = collections.defaultdict(set)
for k in d1:
   merged[k].add( d1[k] )
for k in d2:
   merged[k].add( d2[k] )
+14

, :

>>> d1={'key1':1, 'key2':2}
>>> d2={'key1':1, 'key2':'A', 'key4':4}
>>> d = {}
>>> d.update(d1)
>>> for i in d2:
        if i in d and d2[i] != d[i]:
            d[i] = [d[i], d2[i]]
        else:
            d[i] = d2[i]            
>>> d
{'key2': [2, 'A'], 'key1': 1, 'key4': 4}
+4

, , , ,

, , , , " "

def listify( obj ): 
   if type(obj) != type([]): return [obj]
   else: return obj

def merge( v1, v2 ):
    return listify(v1) + listify(v2)

#so now you can merge two dictionaries:
dict1 = dict(a = 2, b = 5, c = 7 )
dict2 = dict(b = 4, d = 9, f = 10 )
dikt = {}

for k in set( dict1.keys() + dict2.keys() ):
    dikt[k] = merge( dict1.get(k, []), dict2.get(k, []) )
#resutls in:
# {'a': [2], 'c': [7], 'b': [5, 4], 'd': [9], 'f': [10]}

, dict.keys() , set , set( d1.keys(), d2.keys() ) d1 d2

0

@SilentGhost ( ):

>>> d1 = dict(key1=1, key2=2)
>>> d2 = dict(key1=1, key2='A', key4=4)
>>> d = dict(d1)
>>> for k, v2 in d2.iteritems():
...     v = d.get(k, None)
...     d[k] = [v, v2] if v is not None and v != v2 else v2
...
>>> d
{'key2': [2, 'A'], 'key1': 1, 'key4': 4}
0

This may be a little inconvenient because the data structure you are trying to create is not as natural as it could be. For example, instead of some values ​​being single values ​​and some being lists, why not store everything in lists? For example.

{'key1': [1], 'key2': [2, 'A'], 'key4': [4]}

It is possible in Python to have a set of mixed data types, but your code will often be cleaner if you keep it connected. If you use such a data structure, pasting is as easy as

# Inserting a (key, value) pair
if key in my_dict:
    my_dict[key].append(value)
else:
    my_dict[key] = [value]
0
source

Here is another option.

d1 = {'key1'=1, 'key2'=2}
d2 = {'key1'=1, 'key2'='A', 'key4'=4)
d = d2
for k, v in d.iteritems():
... if k in d1.keys() and v!=d1[k]:
... d[k] = [d1[k], v2]
d
{'key2': [2, 'A'], 'key1': 1, 'key4': 4}
0
source

All Articles