推送到远程仓库

在本地开发环境开了个新项目,需要将项目推送到远程仓库(如,bitbucket)。

  • 首先,在本地创建一个 git 创库

$ git init $ git add -A $ git commit -am "xxx"
  • 创建远程仓库

  • 添加关联的远程仓库地址 git remote add origin URL,如:


$ git remote add origin https://lizsBitbucket.org/...
  • 推送到远程仓库

$ git push // 如果该分支为本地新建,而远程仓库没有的 $ git push --set-upstream origin branchName

迁移远程仓库

比如,在项目开发中想要将远程个人的私有仓库,迁移到一个公众账号的仓库中。

  • 远程仓库迁移

  • 本地仓库中更改 git 关联的远程 url 路径,git remote set-url origin URL


$ git remote set-url origin https://lizsBitbucket@bitbucket.org/...

https://... 为仓库的新地址。

本地通知

本地通知:本地通知不依赖网络,无网络条件下依旧可以触发;可以定时发出通知。

Cordova 本地通知,可以用插件 cordova-plugin-local-notification 实现。


# Plugin Registry cordova plugin add de.appplant.cordova.plugin.local-notification # Github cordova plugin add https://github.com/katzer/cordova-plugin-local-notifications

cordova-plugin-local-notification 插件wiki

远程实时通知

远程通知:依赖网络,可以根据需要实时推送通知。

当在某种情况下,你需要向 APP 用户推送消息,而且该用户又没有打开 APP 的时候(后台运行)。你怎样才能够发出消息通知用户呢?

极光推送提供了一个 Cordova 通知插件 jpush-phonegap-plugin,即使 APP 在后台运行状态,也可以实现实时推送通知的功能。


Cordova 插件 jpush-phonegap-plugin 安装 (Android)

  • 先在极光推送官网注册一个账号,然后,在极光开发者服务创建一个应用 (因为,在安装插件的时候会用到 AppKey)。
    • 应用名称:填 Cordova 配置文件config.xml 中的 <name> 即可。

    • 应用包名(Android):填 Cordova 配置文件 config.xml 中的 <widget> 中的 id 即可。

  • Cordova 应用中添加插件:cordova-plugin-devicejpush-phonegap-plugin。要用到 cordova-plugin-device 插件。


# cordova-plugin-device cordova plugin add cordova-plugin-device # jpush-phonegap-plugin cordova plugin add jpush-phonegap-plugin --variable APP_KEY=AppKey # or github cordova plugin add https://github.com/jpush/jpush-phonegap-plugin.git --variable APP_KEY=AppKey

注意:AppKey 就是在极光开发者服务中创建应用之后,在应用信息中的 AppKey


Cordova 插件 jpush-phonegap-plugin 使用

jpush-phonegap-plugin 在需要在 cordova deviceready 的时候初始化才能够使用。初始化之后,正常情况下,会根据设备产生一个 registration ID(相对不同设备具有唯一性)。我们可以将这个 registration ID 保存到服务器端,通过这个 registration ID 对特定用户发送通知。也可以,通过设置 tag 等来实现。更多使用可以查看官方文档:JPush 官方文档

插件的一些常用 Cordova 监听事件,如:

  • jpush.receiveNotification:Cordova APP 在接收到 jpush 远程通知的时候触发事件。

  • jpush.openNotification:点击通知栏的 jpush 远程通知的时候触发事件。


jQuery(function($) { var cordovaJS = { // Application constructor initialize: function() { document.addEventListener('devicerady', this.onDeviceReady.bind(this), false); document.addEventListener('jpush.openNotification', this.jPushOpenNotification.bind(this), false); }, // Application deviceready event onDeviceReady: function() { this.jPushInitEvent(); }, jPushInitEvent: function() { window.plugins.jPushPlugin.init(); // Setting the notification max showing number window.plugins.jPushPlugin.setLatesNotificationNum(5); }, // The event when user click notification jPushOpenNotification: function(receiveObj) { // When click notification, show the message with alert button // Requirement to install cordova plugin: cordova-plugin-dialogs navigator.notification.alert(receiveObj.alert); } }; cordovaJS.initialize(); // Get registration ID window.plugins.jPushPlugin.getRegistrationID(function(id) { // The var id is the registration ID // So you can do something to save it to server here. }); });

正常情况下,初始化完之后,我们就可以在极光推送后台创建的项目中手动发送通知了(发送通知的时候,通知内容一定要填,不然设备不会显示通知)。但是,这不是我们想要的。通常,我们需要在服务器后台根据一定的条件自动触发推送条件,并且推送到特定的用户设备上。插件官方提供了服务端 SDK,我们可以通过安装相应的 SDK,通过调用相关的接口来实现服务器端发送通知的功能。如,Python:

  • 安装 Python SDK

pip/pip3 install jpush
  • 通过安装的 jpush 模块编写发送通知功能, jpush_client.py

import jpush class JPushClient(object): """jPush client for Instrument Connect Requirements: the jpush module must be installed (pip/pip3 install jpush). More info: https://docs.jiguang.cn/jpush/server/3rd/python_sdk/ """ def __init__(self, app_key, master_secret, *args, **kwargs): # AppKey and Master Secret from jiguang project self.app_key = app_key self.master_secret = master_secret def push_notification(self, registration_id, content, *args, **kwargs): """Push notification to user via jPush client: :param registration_id: a list of registration id which binding the user phone :param content: the notification content that will be send to user :return: """ # Init a jPush object _jpush = jpush.JPush(self.app_key, self.master_secret) # Create a push notification push = _jpush.create_push() # Setting push audience push.audience = jpush.audience({ 'registration_id': registration_id }) # Setting push platform push.platform = jpush.all_ # Setting notification content push.notification = jpush.notification(alert=content) push.send()
  • 调用编写好的接口,发送通知:

from xxx.jpush_client import JPushClient # AppKey and Master Secret from your jiguang project app_key = 'your project AppKey' master_secret = 'your project Master Secret' # A list of registration id that you want to send the notification to registration_id = ['xxx', 'xxx'] content = 'hello' JPushClient(app_key, master_secret).push_notification(registration_id, content)

更多 Python SDK 的使用可以查看 ipush-api-python-client

我们运行 cordova build android 的时候,生成的是 debug APK,是没有签名的。没有签名的 APK 不能够在Android 市场上发布的,同时,也不能够进行无缝升级等。

APP 签名作用

  • APP 签名可以保证应用开发者的所有权,防止应用被恶意替换和篡改。

  • APP 必须用同一个证书(*.jks)进行签名,才能够无缝升级安装新的版本。

  • 应用的模块化设计和开发。

  • Android 允许同一个证书签名的应用共享代码和数据。

生成签名证书(*.jks)

使用的是 Android Studio 生成签名证书文件:

  1. 用 Android Studio 打开 Cordova 项目中的 Android 包(platform/android)。

  2. 点击 Android Studio 顶部菜单栏的 【Build】=>【Generate Signed APK…】,会弹出一个【Generate Signed APK】的提示框。

  3. 这个提示框是用来生成签名 APK 的,但是,我们现在还没有签名证书文件。所以,点击其中的【Create new..】选项,会弹出一个【New Key Store】的提示框,生成签名证书文件:

  • Key store path:保存签名证书文件的路径。

  • Password:这个是 Key store password,生成签名 APK 的时候要输入。

  • Key Alias:别名,也是签名文件的名称。

  • Key Password:这个是 Key Password,生成签名 APK 的时候要输入。

其它的一些选项可以根据个人信息填写。填写完之后,点击【OK】,就可以在 Key store path 看到生成了签名文件(*.jks)。

生成签名 APK

使用 Android Studio 生成签名 APK

同样,点击 Android Studio 顶部菜单栏的【Build】=>【Generat Signed APK】:

  • Key store path:这次是点击【Choose existing…】选择刚刚生成的签名证书路径,如 /home/lizs/cordova/lizs.jks

  • Key store password:该签名文件的 Key store password

  • Key alias:签名文件的 Key Alias

  • Key password:该签名文件的 Key Password

填写好之后, 点击【next】进行下一步:

  • APK Destination Folder:生成签名 APK 的保存路径。

  • Build Type:release

最后【Finish】,成功之后会在 APK Destination Folder 生成一个 android-release.apk 的签名 APK。

命令生成签名 APK

手动调用了 Android SDK 中的 apksigner 工具来将 debug APK 生成签名 APK。


zipalign -v -p 4 android-release-unsigned.apk android-release.apk apksigner verify android-release.apk
  • zipalignapksigner 都是 Android SDK 中的 build-tool,如果全局环境变量中没有,需要用全局路径,如 /opt/android-sdk-linux/build-tools/25.0.2/zipalign

  • android-release-unsigned.apk:debug APK

参考:Android Studio 中 Android 应用程序签名打包方法

实践环境:ubuntu14.04

更新系统数据:


$ sudo apt-get update $ sudo apt-get upgrade

Nginx


$ sudo apt-get install nginx

成功安装之后,启动 Nginx 之后,访问localhost(127.0.0.1)会显示欢迎页面。

MySQL


$ sudo apt-get install mysql-server php5-mysql

如果需要,可以安装 phpmyadmin


$ sudo apt-get install phpmyadmin

PHP5

  • 安装 PHP5

$ sudo apt-get install php5-fpm

也可以同时安装其他 php5 库。


$ sudo apt-get install php5-fpm php5-cli php5-mysql php5-gd php5-mcrypt php5-curl

php5-cli:Command Line Interface,命令行界面。如果没有安装,你想要在终端执行 php 命令,或者执行一个 php 脚本文件(#!/usr/bin/php)等都是无法执行的。

php5-mysql:php5 的 mysql 数据库扩展,提供 php 能够访问 mysql 的接口。

php5-gd:gd 库是 php 处理图形的扩展库,gd 库提供了一系列用来处理图片的 API。

php5-mcrypt:php5 加密函数库

  • 配置 php5-fpm

更改配置文件 /etc/php5/fpm/php.inicgi.fix_pathinfo 的值为 0,然后,重启 php5-fpm 服务。

  • 配置 Nginx

配置 Nginx,是它支持 php 文件。

文件:/etc/nginx/sites-available/default


location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; # # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini # # # With php5-cgi alone: # fastcgi_pass 127.0.0.1:9000; # # With php5-fpm: fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; }

然后,重新载入 Nginx 配置:service nginx reload

PHP7

  • 添加 PPA(Personal Package Archives)

sudo apt-get install python-software-properties software-properties-common sudo add-apt-repository ppa:ondrej/php sudo apt-get update
  • 安装 php7.0

sudo apt-get install php7.0-fpm

也可同时安装 php7.0 的一些扩展


sudo apt-get install php7.0-fpm php7.0-mysql php7.0-cli php7.0-curl php7.0-mcrypt
  • 配置 php7.0-fpm

更改配置文件 /etc/php/7.0/fpm/php.inicgi.fix_pathinfo 的值为 0,然后,重启 php7-fpm 服务。

  • 配置 Nginx

location ~ \.php$ { fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; fastcgi_index index.php; include fastcgi_params; }

systemctl (centos7)

  • 启动服务:
    systemctl start x.service
    
  • 关闭服务:
    systemctl stop x.service
    
  • 重启服务:
    systemctl restart x.service
    
  • 查看服务状态:
    systemctl status x.service
    
  • 开机启动服务:
    systemctl enable x.service
    
  • 开机不启动服务:
    systemctl disable x.service
    
  • 查看所有服务:
    systemctl list-units --type=service 
    

ntpdate

  • 更新服务器时间
    ntpdate -u ntp.api.bz
    

    ntp.api.bz: NTP 服务器(上海)

tuple

Tuples are immutable sequences.

tuple([iterable])

The constructor builds a tuple whose items are the same and
in the same order as iterable‘s items.

iterable may be a sequence,
a container that supports iteration, or an iterable object.

If iterable is already a tuple, it is returned unchanged.

  • Empty tuple: (), tuple()
  • Singleton tuple: 'a',, (‘a’,)
  • Multiple elements tuple: 'a', 0, ('a', 0), tuple(iterable)
  • t.count(x)

    return number of occurrences of x, if no x in the tuple
    a 0 value will be returned.

  • t.index(x, start=None, stop=None)

    Return first index of x. Raises ValueError if the x is not present.

class tuple(object):
    """
    tuple() -> empty tuple
    tuple(iterable) -> tuple initialized from iterable's items

    If the argument is a tuple, the return value is the same object.
    """
    def count(self, value): # real signature unknown; restored from __doc__
        """ T.count(value) -> integer -- return number of occurrences of value """
        return 0

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        T.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

    def __add__(self, *args, **kwargs): # real signature unknown
        """ Return self+value. """
        pass

    def __contains__(self, *args, **kwargs): # real signature unknown
        """ Return key in self. """
        pass

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __getitem__(self, *args, **kwargs): # real signature unknown
        """ Return self[key]. """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass

    def __hash__(self, *args, **kwargs): # real signature unknown
        """ Return hash(self). """
        pass

    def __init__(self, seq=()): # known special case of tuple.__init__
        """
        tuple() -> empty tuple
        tuple(iterable) -> tuple initialized from iterable's items

        If the argument is a tuple, the return value is the same object.
        # (copied from class doc)
        """
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass

    def __mul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value.n """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    def __rmul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value. """
        pass

list

  • list() new empty list
  • list(iterable) new list initialized from iterable’s items

The constructor builds a list whose items are the same and
in the same order as iterable’s items.

iterable may be either a sequence, a container that supports iteration,
or an iterator object. If iterable is already a list, a copy is made and returned,
similar to iterable[:]. e.g. list('abc') => ['a', 'b', 'c'],
list(range(2)) => [0, 1], list([0, 1]) => [0, 1].

Create

  • l.copy() # New in Python3

    Return a shallow copy of l.

  • l.append(p_object)

    Append object to the end of l.

  • l.insert(index, p_object)

    Insert object before index.

  • l.extend(iterable)

    Extend list by appending elements from iterable.

Delete

  • l.pop([index])

    Remove and return item at index (default last).
    Raises IndexError if list is empty or index is out of range.

  • l.remove(value)

    Remove first occurrence of value.
    Raises ValueError if the value is not present.

  • l.clear() # New in Python3

    Return a shallow copy of l.

Retrieve

  • l.count(value)

    Return number of occurrences of value.

  • l.index(value, [start[, stop]])

    Return first index of value.

Update

  • l.reverse()

Reverse IN PLACE. e.g.

l = [0, 1, 2]
l.reverse()   # No list return, but reverse in place
print(l)
[2, 1, 0]
  • l.sort([key, reverse])

Sorts the list l in place.

sort() accepts two arguments that can only be passed by keyword (keyword-only arguments).

Error: l.sort(lambda x: x == 2), l.sort(lambda x: x == 2, True)

True: l.sort(key=lambda x: x == 2), l.sort(key=lambda x: x == 2, reverse=True)

key, specifies a function of one argument that is used to extract a
comparision key from each list element (e.g. key=str.lower).

The smaller of the key function return value, the corresponding item is more forward.
And the True indicate int 1, False indicate int 0.

l = [5, 1, 2, 4, 0]
l.sort(key=lambda x: x == 2)
print(l)
[5, 1, 4, 0, 2]   # 2 => True(1); others => False(0)
l.sort(key=lambda x: x)
print(l)
[0, 1, 2, 4, 5]
class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """
    def append(self, p_object):
        """ L.append(object) -> None -- append object to end """
        pass

    def clear(self): # New in Python3
        """ L.clear() -> None -- remove all items from L """
        pass

    def copy(self): # New in Python3
        """ L.copy() -> list -- a shallow copy of L """
        return []

    def count(self, value):
        """ L.count(value) -> integer -- return number of occurrences of value """
        return 0

    def extend(self, iterable):
        """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
        pass

    def index(self, value, start=None, stop=None):
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

    def insert(self, index, p_object):
        """ L.insert(index, object) -- insert object before index """
        pass

    def pop(self, index=None):
        """
        L.pop([index]) -> item -- remove and return item at index (default last).
        Raises IndexError if list is empty or index is out of range.
        """
        pass

    def remove(self, value):
        """
        L.remove(value) -> None -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        pass

    def reverse(self):
        """ L.reverse() -- reverse *IN PLACE* """
        pass

    def sort(self, key=None, reverse=False):
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
        pass

    def __add__(self, *args, **kwargs):
        """ Return self+value. """
        pass

    def __contains__(self, *args, **kwargs):
        """ Return key in self. """
        pass

    def __delitem__(self, *args, **kwargs):
        """ Delete self[key]. """
        pass

    def __eq__(self, *args, **kwargs):
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs):
        """ Return getattr(self, name). """
        pass

    def __getitem__(self, y):
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __ge__(self, *args, **kwargs):
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs):
        """ Return self>value. """
        pass

    def __iadd__(self, *args, **kwargs):
        """ Implement self+=value. """
        pass

    def __imul__(self, *args, **kwargs):
        """ Implement self*=value. """
        pass

    def __init__(self, seq=()):
        """
        list() -> new empty list
        list(iterable) -> new list initialized from iterable's items
        # (copied from class doc)
        """
        pass

    def __iter__(self, *args, **kwargs):
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs):
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs):
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs):
        """ Return self<value. """
        pass

    def __mul__(self, *args, **kwargs):
        """ Return self*value.n """
        pass

    @staticmethod
    def __new__(*args, **kwargs):
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs):
        """ Return self!=value. """
        pass

    def __repr__(self, *args, **kwargs):
        """ Return repr(self). """
        pass

    def __reversed__(self):
        """ L.__reversed__() -- return a reverse iterator over the list """
        pass

    def __rmul__(self, *args, **kwargs):
        """ Return self*value. """
        pass

    def __setitem__(self, *args, **kwargs):
        """ Set self[key] to value. """
        pass

    def __sizeof__(self):
        """ L.__sizeof__() -- size of L in memory, in bytes """
        pass

    __hash__ = None


set

A set object is an unordered collection of distinct hashable objects.

Like other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.

There are currently two built-in set types, set and frozenset.

  • set([iterable]) – Return a set. The elements of a set must be hashable, bue the set type itself is mutable. The contents can be changed using methods like add() and remove(). Since set type is mutable, it has no hash value and cannot be used as either a dictionary key or and element of another set.

    Non-empty sets(not frozensets) also can be created by placing a comma-separated list of elements within braces, for example: {'jack', 'lizs'}, in addition to the set constructor.

  • frozenset([iterable]) – Return a frozenset. The elements of frozenset must be hashable and the frozenset type is immutable and hashable. its contents cannot be altered after it is created, it can therefore be used as a dictionary key or as an element of another set.

  • len(S) # set/frozenset

    Return the member of elements in set s (cardinality of s).

  • x in s # set/frozenset

  • x not in s # set/frozenset

  • isdisjoint(other) # set/frozenset

    Return True if the set has no elements in common with other.
    Sets are disjoint if and only if their intersection is the empty set.

  • issubset(other)

  • set <= other

    Test whether every element in set is in other.

  • set < other

    Test whether the set is a proper subset of other, that is set <= other and set != other.

  • issuperset(other)

  • set >= other

    Test whether every element in other is in the set.

  • set > other

    Test whether the set is a proper superset of other, that is, set >= other and set != other.

  • s.union(*other)

  • set | other

    Return a new set with elements from the set and all others.

  • s.intersection(*other)

  • set & other

    Return a new set with elements common to the set and all others.

  • s.difference(*others)

  • set – other

    Return a new set with elements in the set that are not in the others.

  • s.symmetric_difference(other)

  • set ^ other

    Return a new set with elements in either the set or other but not both.

  • s.copy()

    Return a new set with a shallow copy of s.

Note, the non-operator versions of union(), intersection(), difference(),
and symmetric_difference(), issubset(), and issupperset() methods will
accept any iterable as an argument. In contrast, their operator based counterparts
require their arguments to be sets.

Instance of set are compared to instances of frozenset based on their members.
e.g. set('abc') == frozenset('abc') return True and so does set('abc') in set([frozenset('abc')])

Binary operations that mix set instances with frozenset return the type of first operand.
e.g. frozenset('ab') | set('bc') returns an instance of frozenset

The following table lists operations available for set that do not apply to immutable instances of frozenset:

  • s.update(*other)
  • set |= other

    Update the set, adding elements from all others.

  • s.intersection_update(*other)

  • set &= other

    Update the set, keeping only elements found in it and all others.

  • s.difference_update(*other)

  • set -= other

    Update the set, removing the elements found in others.

  • s.symmetric_difference_update(*other)

  • set ^= other

    Update the set, keeping only elements found in either set, but not in both.

  • s.add(elem) # set

    Add element elem to the set.

  • s.discard(elem)

    Remove element elem from the set if it is present.

  • s.remove(elem)

    Remove element elem from the set. Raises KeyError if elem is not contained in the set.

  • s.pop()

    Remove and return an arbitrary element from the set. Raises KeyError if the set is empty.

  • s.clear()

    Remove all elements from the set.

Note, the non-operator versions of update(), intersection_update(),
difference_update(), symmetric_difference_update() methods will accept
any iterable as an argument.

class dict(object):

  • dict() -> new empty dictionary.
  • dict(**kwargs) -> new dictionary initialized with the
    name=value pairs in the keyword argument list. e.g. dict(a=1, b=2).
  • dict(mapping, **kwargs) -> new dictionary initialized from a
    mapping object’s (key, value) pairs. e.g. {'a': 1}, dict({'a': 1}).
  • dict(iterable, **kwargs) -> new dictionary iterable object.
    Each item in the iterable must itself be an iterable with exactly two objects.
    e.g. dict([('a', 1)]), dict([('a', 1), ('b', 2)]).

If the key is duplicated, the value from the keyword argument replaces
the value from the positional argument.
e.g. dict([('a', 0), ('b', 2)], a=1, c=3) <=> {'a': 1, 'b': 2, 'c': 3}

  • len(d)

  • del d[key]

  • iter(d)

    Return an iterator over the keys of the dictionary.
    This is the shortcut for iter(d.keys())(Python3)/iterkeys()(Python2).

Create

  • d.copy()

    Return a shallow copy of the dictionary.

  • d.fromkeys(seq[, value])

    Create a new dictionary with keys from seq and all of values set to value.
    fromkeys() is a class method that return a new dictionary. value defaults to None.

Delete

  • d.clear()

    Remove all items from the dictionary.

  • d.pop(key[, default])

    If the key in the dictionary, remove it and return its value, else return default.
    If default is not given and key is not in the dictionary, a KeyError is raised.

  • d.popitem()

    Remove and return a arbitrary (key, value) pair from dictionary.
    If the dictionary is empty, calling popitem() raises a KeyError.

Update

  • d.update([other])

    Update the dictionary with the key/value pairs from other,
    overwriting the existing keys. Return None.
    update() accepts either another dictionary object or an iterable of
    key/value pairs (as tuple or other iterables of length two).
    If the keyword arguments are specified, the dictionary is then updated
    with those key/value pairs: d.update(red=1, blue=2).

  • d.setdefault(key[, default])

    If the key in the dictionary, return its value. If not, insert key with
    a value of default and return default, default defaults to None.

Retrieve

  • d.get(key[, default])
    > Return the value for key if key is in the dictionary, else default.
    If default is not given, it defaults to None, so that this method never raises a KeyError.

Python3

  • d.keys()

    Return a new view of the dictionary’s keys.

  • d.values()

    Return a new view of the dictionary’s values.

  • d.items()

    Return a new view of the dictionary’s items ((key, value) pairs).

Dictionaries compare equal if and only if they have the same (key, value) pairs.
Order comparisons(‘<‘, ‘<=’, ‘>’, ‘>=’) raise TypeError.

Python2

  • d.keys()

    Return a copy of dictionary’s list of keys.

  • d.values()

    Return a copy of dictionary’s list of values.

  • d.items()

    Return a copy of dictionary’s list of (key, value) pairs.

  • d.viewkeys()

    Return a new view of the dictionary’s keys.

  • d.viewvalues()

    Return a new view of the dictionary’s values.

  • d.viewitems()

    Return a new view of the dictionary’s items ((key, value) pairs).

  • d.iterkeys()

    Return a iterator over the dictionary’s keys.

  • d.itervalues()

    Return a iterator over the dictionary’s values.

  • d.iteritems()

    Return a iterator over the dictionary’s (key, value) pairs.

  • d.has_key(key)

    Test for the presence of key in the dictionary.
    has_key() is deprecated in favor of key in d.

Dictionary view objects

The objects returned by dict.keys(), dict.values() and dict.items()
(Python2: dict.viewkeys(), dict.viewvalues() and dict.viewitems()) are view object.

They provide a dynamic view on the dictionary’s entries, which means that
when dictionary change, the view reflects these changes.

# Python3
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
keys = d.keys()
print(keys) # ['a', 'b', 'c', 'd']
del d['d']
print(keys) # ['a', 'b', 'c']
  • len(dictview)

    Return the number of entries in the dictionary.

  • iter(dictview)

    Return an iterator over the keys, values or items
    (represented as tuples of (key, value)) in the dictionary.
    Iterating views while adding or deleting entries in the dictionary may
    raise a RuntimeError or fail to iterate over all entries.

  • x in dictview

    Return True if x is in the underlying dictionary’s keys, values or
    items (in the latter case, x should be a (key, value) tuple).

Keys and items views are set-like since their entries are unique and hashable.
Values views are not treated as set-like since the entries are generally not unique.
For set-like views, all of the operations defined for the set are available(e.g. &, |, -, ^).

class dict(object):    # Python3
    """
    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)
    """
    def clear(self):
        """ D.clear() -> None.  Remove all items from D. """
        pass

    def copy(self):
        """ D.copy() -> a shallow copy of D """
        pass

    @staticmethod # known case
    def fromkeys(*args, **kwargs):
        """ Returns a new dict with keys from iterable and values equal to value. """
        pass

    def get(self, k, d=None):
        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass

    def items(self):
        """ D.items() -> a set-like object providing a view on D's items """
        pass

    def keys(self):
        """ D.keys() -> a set-like object providing a view on D's keys """
        pass

    def pop(self, k, d=None):
        """
        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised
        """
        pass

    def popitem(self):
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass

    def setdefault(self, k, d=None):
        """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
        pass

    def update(self, E=None, **F):
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        """
        pass

    def values(self):
        """ D.values() -> an object providing a view on D's values """
        pass

    def __contains__(self, *args, **kwargs):
        """ True if D has a key k, else False. """
        pass

    def __delitem__(self, *args, **kwargs):
        """ Delete self[key]. """
        pass

    def __eq__(self, *args, **kwargs):
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs):
        """ Return getattr(self, name). """
        pass

    def __getitem__(self, y):
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __ge__(self, *args, **kwargs):
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs):
        """ Return self>value. """
        pass

    def __init__(self, seq=None, **kwargs):
        """
        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)
        # (copied from class doc)
        """
        pass

    def __iter__(self, *args, **kwargs):
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs):
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs):
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs):
        """ Return self<value. """
        pass

    @staticmethod
    def __new__(*args, **kwargs):
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs):
        """ Return self!=value. """
        pass

    def __repr__(self, *args, **kwargs):
        """ Return repr(self). """
        pass

    def __setitem__(self, *args, **kwargs):
        """ Set self[key] to value. """
        pass

    def __sizeof__(self):
        """ D.__sizeof__() -> size of D in memory, in bytes """
        pass

    __hash__ = None