python dictionaries and objects

Keywords: Python Attribute Java

python dictionary

N Methods for Dictionary Initialization

  • Direct assignment

    a = {"one": 1, "two": 2, "three": 3}
  • Create a new dictionary object before assigning it dynamically

    b = dict()
    b["one"] = 1
    b["two"] = 2
    b["three"] = 3
  • When creating a new dictionary object, assign values by parameters

    c = dict(one=1, two=2, three=3)
  • When creating a new dictionary object, assign values through nested tuples and lists

    d = dict([("one", 1), ("two", 2), ("three", 3)])
  • Through the zip function

    e = dict(zip(["one", "two", "three"], [1, 2, 3]))
    list(zip(["one", "two", "three"], [1, 2, 3]))
    <<< [("one", 1), ("two", 2), ("three", 3)]
    zip()function:Package the corresponding elements in the object into tuples and return a list of those tuples

    To reduce memory in Python 3.x, zip() returns an object.To show a list, you need to convert the list() manually.

  • Create a new dictionary object so that it is passed directly into the dictionary object as a parameter

    f = dict({"one": 1, "two": 2, "three": 3})
  • Use fromkeys() to assign the same value to all keys in a dictionary

    g = dict.fromkeys(["height", "weight"], "normal")
    g = dict.fromkeys(("height", "weight"), "normal")
    <<< {'height': 'normal', 'weight': 'normal'}

    If the second parameter is not specified, all keys correspond to a value of None

Graceful key acquisition

# A dictionary can get the value of a key like this
info= {'a': 1, 'b': 2}
<<< 1
# In the above way, getting the value of a key that does not exist triggers a KeyError exception
# A dictionary has a get method that allows you to gracefully get the value of the corresponding key in the dictionary
info= {'a': 1, 'b': 2}
<<< 1
<<< None
info.get('c', 3)
<<< 3

Update of Dictionary

# update method
dict_a = {'a': 1, 'b': 2}
dict_b = {'a': 5, 'c': 7}
<<< {'a': 5, 'b': 2, 'c': 7}

Delete Dictionary Key Values

# del built-in keyword
dict_a = {'a': 1, 'b': 2}
del dict_a['a']
<<< {'b': 2}

# The pop method of the dictionary
dict_a = {'a': 1, 'b': 2}
<<< 1
<<< {'b': 2}

Get all key s and value s

dict_a = {'a': 1, 'b': 2, 'c': 3}
# Get all keys
<<< dict_keys(['a', 'b', 'c'])
# Get all value s
<<< dict_values([1, 2, 3])
# Get all key-value pairs
<<< dict_items([('a', 1), ('b', 2), ('c', 3)])

Note: The above method returns a list that is not a real list and cannot be indexed directly. You can use the for loop to get the value or add a list() on the outer layer to convert it to a real list, that is, list(dict_a.keys()).

I thought the above method would return an iterator, but I tried using the next() method and proved that it is not an iterator, just to put iterator and generator in a nutshell.

TypeError: 'dict_keys' object is not an iterator

  • generator (calculating while looping, unknown sequence length, inertia)

    If a function type contains the yieldkeyword, it is a generator.Executed each time next() is called, yielded statement returns are encountered, and executed again from the last statement that returned yield.

  • Iterable Objects

    You can use for loops, but you cannot use next(), such as list,tuple,dict,set,str.

  • Iterator

    You can use for and next(), for example, a generator; and iter(), you can make Iterable an Iterator.



# The u slots_u attribute restricts the properties of the object and does not allow private modification of types and numbers
class Test(object):
    __slots__ = ['a', 'b', 'c'] # or ('a', 'b', 'c')
t = Test()
t.d = 4
AttributeError: 'Test' object has no attribute 'd'
AttributeError: b
# In other words, u slots_ simply restricts the properties of the object, but it has not really determined to add these properties to the object.


# Class has a special method (construction method) called u init_(), which is called automatically when the class is instantiated
class Test(object):
    __slots__ = ['a', 'b', 'c']
    def __init__(self):
    	self.a = '1'

t = Test()
<<< 1
# Of course, the u init_u() method can have parameters that are passed to the instantiation of a class through u init_()
class Test(object):
    __slots__ = ['a', 'b', 'c']
    def __init__(self, a, b):
    	self.a = a
        self.b = b
t = Test(100, 200)
<<< 100 

Note: self represents an instance of a class, not a class

Meaning of''and u'

Variables or methods starting with''are protected and can only be accessed by themselves and subclasses.

Variables or methods that start with u are private and can only be accessed by the class itself;

Note: u xx_ is a special variable or method, not a private variable


  • hasattr(obj, target)
  • getattr(obj, target, default)
  • setattr(obj, target, default)
class Test1(object):

    __slots__ = ('a', 'b', 'c')

# Show all properties of this class as defined and assign an initial value (Initial Value 1)
test = Test1()
for key in test.__slots__:
    setattr(test, key, 1)

# Check whether the object contains target attributes
print(hasattr(test, 'a'))
<<< True
print(hasattr(test, 'd'))
<<< False

# Get the target attribute value
print(getattr(test, 'b'))
<<< 1
print(getattr(test, 'd'))
AttributeError: 'Test1' object has no attribute 'd'
# As you can see, the getattr method does not get any properties that will cause errors and can be resolved by setting default values
print(getattr(test, 'd', 1))
<<< 1

Object to Dictionary

class Test1(object):    
    __slots__ = ('a', 'b', 'c')

test = Test1()
test.a = 1
test.b = 2

# Convert object test to dictionary
result = dict()
for key in test.__slots__:
    # Default values must be set here, or errors will most likely occur, such as the absence of a display definition for property c in this example
    result[key] = getattr(test, key, '')
<<< {'a': 1, 'b': 1, 'c': ''}

Trinomial operations in python

In C/C++/C# or Java, there are trinomial operators, conditional expression 1? Expression 1: expression 2;

Means that if the conditional expression 1 value is true, the entire expression is evaluated as expression 1, otherwise it is evaluated as expression 2.

python does not have the form a?b:c, but it has a similar expression, a if b else c, which means that if B is true, it returns a, otherwise it returns C.

a = 10
b = 20
c = a if True else b
d = a if False else b
<<< 10
<<< 20

Posted by Jeannie109 on Sun, 08 Sep 2019 18:58:08 -0700