一、创建增加修改

1、实现代码

  1. #创建
  2. stu_info = { "xiedi":28, "liuhailin":27,"daiqiao":30,"hanwenhai":25,"chenqun":38}
  3. print(stu_info)
  4. #增加
  5. stu_info["luoahong"]=32
  6. print(stu_info)
  7. #修改
  8. stu_info["xiedi"]=29
  9. print(stu_info)

输出结果

  1. {'xiedi': 28, 'liuhailin': 27, 'daiqiao': 30, 'hanwenhai': 25, 'chenqun': 38}
  2. {'xiedi': 28, 'liuhailin': 27, 'daiqiao': 30, 'hanwenhai': 25, 'chenqun': 38, 'luoahong': 32}
  3. {'xiedi': 29, 'liuhailin': 27, 'daiqiao': 30, 'hanwenhai': 25, 'chenqun': 38, 'luoahong': 32}

二、删除(del)

1、实现代码

  1. del stu_info["chenqun"]
  2. print(stu_info)

2、输出结果

  1. {'xiedi': 29, 'liuhailin': 27, 'daiqiao': 30, 'hanwenhai': 25, 'luoahong': 32}

1、Dict_DelItem

  1. int
  2. PyDict_DelItem(PyObject *op, PyObject *key)
  3. {
  4. Py_hash_t hash;
  5. assert(key);
  6. if (!PyUnicode_CheckExact(key) ||
  7. (hash = ((PyASCIIObject *) key)->hash) == -1) {
  8. hash = PyObject_Hash(key);
  9. if (hash == -1)
  10. return -1;
  11. }
  12.  
  13. return _PyDict_DelItem_KnownHash(op, key, hash);
  14. }

2、Dict_DelItem_KnownHash

  1. int
  2. _PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
  3. {
  4. Py_ssize_t ix;
  5. PyDictObject *mp;
  6. PyObject *old_value;
  7.  
  8. if (!PyDict_Check(op)) {
  9. PyErr_BadInternalCall();
  10. return -1;
  11. }
  12. assert(key);
  13. assert(hash != -1);
  14. mp = (PyDictObject *)op;
  15. ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
  16. if (ix == DKIX_ERROR)
  17. return -1;
  18. if (ix == DKIX_EMPTY || old_value == NULL) {
  19. _PyErr_SetKeyError(key);
  20. return -1;
  21. }
  22.  
  23. // Split table doesn't allow deletion. Combine it.
  24. if (_PyDict_HasSplitTable(mp)) {
  25. if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
  26. return -1;
  27. }
  28. ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
  29. assert(ix >= 0);
  30. }
  31.  
  32. return delitem_common(mp, hash, ix, old_value);
  33. }
  34.  
  35. /* This function promises that the predicate -> deletion sequence is atomic
  36. * (i.e. protected by the GIL), assuming the predicate itself doesn't
  37. * release the GIL.
  38. */

3、PyDict_DelItemIf

  1. int
  2. _PyDict_DelItemIf(PyObject *op, PyObject *key,
  3. int (*predicate)(PyObject *value))
  4. {
  5. Py_ssize_t hashpos, ix;
  6. PyDictObject *mp;
  7. Py_hash_t hash;
  8. PyObject *old_value;
  9. int res;
  10.  
  11. if (!PyDict_Check(op)) {
  12. PyErr_BadInternalCall();
  13. return -1;
  14. }
  15. assert(key);
  16. hash = PyObject_Hash(key);
  17. if (hash == -1)
  18. return -1;
  19. mp = (PyDictObject *)op;
  20. ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
  21. if (ix == DKIX_ERROR)
  22. return -1;
  23. if (ix == DKIX_EMPTY || old_value == NULL) {
  24. _PyErr_SetKeyError(key);
  25. return -1;
  26. }
  27.  
  28. // Split table doesn't allow deletion. Combine it.
  29. if (_PyDict_HasSplitTable(mp)) {
  30. if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
  31. return -1;
  32. }
  33. ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
  34. assert(ix >= 0);
  35. }
  36.  
  37. res = predicate(old_value);
  38. if (res == -1)
  39. return -1;
  40.  
  41. hashpos = lookdict_index(mp->ma_keys, hash, ix);
  42. assert(hashpos >= 0);
  43.  
  44. if (res > 0)
  45. return delitem_common(mp, hashpos, ix, old_value);
  46. else
  47. return 0;
  48. }

二、删除pop(k)

实现

  1. stu_info = { "xiedi":28, "liuhailin":27,"daiqiao":30,"hanwenhai":25,"chenqun":38}
  2. print(stu_info)
  3. stu_info.pop("liuhailin")
  4. print(stu_info)

输出结果:

  1. {'xiedi': 28, 'liuhailin': 27, 'daiqiao': 30, 'hanwenhai': 25, 'chenqun': 38}
  2. {'xiedi': 28, 'daiqiao': 30, 'hanwenhai': 25, 'chenqun': 38}

1、_PyDict_Pop

  1. PyObject *
  2. _PyDict_Pop(PyObject *dict, PyObject *key, PyObject *deflt)
  3. {
  4. Py_hash_t hash;
  5.  
  6. if (((PyDictObject *)dict)->ma_used == 0) {
  7. if (deflt) {
  8. Py_INCREF(deflt);
  9. return deflt;
  10. }
  11. _PyErr_SetKeyError(key);
  12. return NULL;
  13. }
  14. if (!PyUnicode_CheckExact(key) ||
  15. (hash = ((PyASCIIObject *) key)->hash) == -1) {
  16. hash = PyObject_Hash(key);
  17. if (hash == -1)
  18. return NULL;
  19. }
  20. return _PyDict_Pop_KnownHash(dict, key, hash, deflt);
  21. }

2、_PyDict_Pop_KnownHash

  1. /* Internal version of dict.pop(). */
  2. PyObject *
  3. _PyDict_Pop_KnownHash(PyObject *dict, PyObject *key, Py_hash_t hash, PyObject *deflt)
  4. {
  5. Py_ssize_t ix, hashpos;
  6. PyObject *old_value, *old_key;
  7. PyDictKeyEntry *ep;
  8. PyDictObject *mp;
  9.  
  10. assert(PyDict_Check(dict));
  11. mp = (PyDictObject *)dict;
  12.  
  13. if (mp->ma_used == 0) {
  14. if (deflt) {
  15. Py_INCREF(deflt);
  16. return deflt;
  17. }
  18. _PyErr_SetKeyError(key);
  19. return NULL;
  20. }
  21. ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
  22. if (ix == DKIX_ERROR)
  23. return NULL;
  24. if (ix == DKIX_EMPTY || old_value == NULL) {
  25. if (deflt) {
  26. Py_INCREF(deflt);
  27. return deflt;
  28. }
  29. _PyErr_SetKeyError(key);
  30. return NULL;
  31. }
  32.  
  33. // Split table doesn't allow deletion. Combine it.
  34. if (_PyDict_HasSplitTable(mp)) {
  35. if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
  36. return NULL;
  37. }
  38. ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
  39. assert(ix >= 0);
  40. }
  41.  
  42. hashpos = lookdict_index(mp->ma_keys, hash, ix);
  43. assert(hashpos >= 0);
  44. assert(old_value != NULL);
  45. mp->ma_used--;
  46. mp->ma_version_tag = DICT_NEXT_VERSION();
  47. dictkeys_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
  48. ep = &DK_ENTRIES(mp->ma_keys)[ix];
  49. ENSURE_ALLOWS_DELETIONS(mp);
  50. old_key = ep->me_key;
  51. ep->me_key = NULL;
  52. ep->me_value = NULL;
  53. Py_DECREF(old_key);
  54.  
  55. ASSERT_CONSISTENT(mp);
  56. return old_value;
  57. }

三、随机删除一个元素popitem()

  1. stu_info = { "xiedi":28, "liuhailin":27,"daiqiao":30,"hanwenhai":25,"chenqun":38}
  2. print(stu_info)
  3. stu_info.popitem()
  4. print(stu_info)

输出结果:

  1. {'xiedi': 28, 'liuhailin': 27, 'daiqiao': 30, 'hanwenhai': 25, 'chenqun': 38}
  2. {'xiedi': 28, 'liuhailin': 27, 'daiqiao': 30, 'hanwenhai': 25}

1、dict_popitem_impl

  1. /*[clinic input]
  2. dict.popitem
  3.  
  4. Remove and return a (key, value) pair as a 2-tuple.
  5.  
  6. Pairs are returned in LIFO (last-in, first-out) order.
  7. Raises KeyError if the dict is empty.
  8. [clinic start generated code]*/
  9.  
  10. static PyObject *
  11. dict_popitem_impl(PyDictObject *self)
  12. /*[clinic end generated code: output=e65fcb04420d230d input=1c38a49f21f64941]*/
  13. {
  14. Py_ssize_t i, j;
  15. PyDictKeyEntry *ep0, *ep;
  16. PyObject *res;
  17.  
  18. /* Allocate the result tuple before checking the size. Believe it
  19. * or not, this allocation could trigger a garbage collection which
  20. * could empty the dict, so if we checked the size first and that
  21. * happened, the result would be an infinite loop (searching for an
  22. * entry that no longer exists). Note that the usual popitem()
  23. * idiom is "while d: k, v = d.popitem()". so needing to throw the
  24. * tuple away if the dict *is* empty isn't a significant
  25. * inefficiency -- possible, but unlikely in practice.
  26. */
  27. res = PyTuple_New(2);
  28. if (res == NULL)
  29. return NULL;
  30. if (self->ma_used == 0) {
  31. Py_DECREF(res);
  32. PyErr_SetString(PyExc_KeyError, "popitem(): dictionary is empty");
  33. return NULL;
  34. }
  35. /* Convert split table to combined table */
  36. if (self->ma_keys->dk_lookup == lookdict_split) {
  37. if (dictresize(self, DK_SIZE(self->ma_keys))) {
  38. Py_DECREF(res);
  39. return NULL;
  40. }
  41. }
  42. ENSURE_ALLOWS_DELETIONS(self);
  43.  
  44. /* Pop last item */
  45. ep0 = DK_ENTRIES(self->ma_keys);
  46. i = self->ma_keys->dk_nentries - 1;
  47. while (i >= 0 && ep0[i].me_value == NULL) {
  48. i--;
  49. }
  50. assert(i >= 0);
  51.  
  52. ep = &ep0[i];
  53. j = lookdict_index(self->ma_keys, ep->me_hash, i);
  54. assert(j >= 0);
  55. assert(dictkeys_get_index(self->ma_keys, j) == i);
  56. dictkeys_set_index(self->ma_keys, j, DKIX_DUMMY);
  57.  
  58. PyTuple_SET_ITEM(res, 0, ep->me_key);
  59. PyTuple_SET_ITEM(res, 1, ep->me_value);
  60. ep->me_key = NULL;
  61. ep->me_value = NULL;
  62. /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
  63. self->ma_keys->dk_nentries = i;
  64. self->ma_used--;
  65. self->ma_version_tag = DICT_NEXT_VERSION();
  66. ASSERT_CONSISTENT(self);
  67. return res;
  68. }

四、查找(key值在字典中存在)

1、dict_keys

  1. static PyObject *
  2. dict_keys(PyDictObject *mp)
  3. {
  4. PyObject *v;
  5. Py_ssize_t i, j;
  6. PyDictKeyEntry *ep;
  7. Py_ssize_t n, offset;
  8. PyObject **value_ptr;
  9.  
  10. again:
  11. n = mp->ma_used;
  12. v = PyList_New(n);
  13. if (v == NULL)
  14. return NULL;
  15. if (n != mp->ma_used) {
  16. /* Durnit. The allocations caused the dict to resize.
  17. * Just start over, this shouldn't normally happen.
  18. */
  19. Py_DECREF(v);
  20. goto again;
  21. }
  22. ep = DK_ENTRIES(mp->ma_keys);
  23. if (mp->ma_values) {
  24. value_ptr = mp->ma_values;
  25. offset = sizeof(PyObject *);
  26. }
  27. else {
  28. value_ptr = &ep[0].me_value;
  29. offset = sizeof(PyDictKeyEntry);
  30. }
  31. for (i = 0, j = 0; j < n; i++) {
  32. if (*value_ptr != NULL) {
  33. PyObject *key = ep[i].me_key;
  34. Py_INCREF(key);
  35. PyList_SET_ITEM(v, j, key);
  36. j++;
  37. }
  38. value_ptr = (PyObject **)(((char *)value_ptr) + offset);
  39. }
  40. assert(j == n);
  41. return v;
  42. }

2、PyDict_Keys

  1. PyObject *
  2. PyDict_Keys(PyObject *mp)
  3. {
  4. if (mp == NULL || !PyDict_Check(mp)) {
  5. PyErr_BadInternalCall();
  6. return NULL;
  7. }
  8. return dict_keys((PyDictObject *)mp);
  9. }
  10.  
  11. PyObject *
  12. PyDict_Values(PyObject *mp)
  13. {
  14. if (mp == NULL || !PyDict_Check(mp)) {
  15. PyErr_BadInternalCall();
  16. return NULL;
  17. }
  18. return dict_values((PyDictObject *)mp);
  19. }

五、get(k)

1、dict_get_impl

  1. static PyObject *
  2. dict_get_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
  3. /*[clinic end generated code: output=bba707729dee05bf input=279ddb5790b6b107]*/
  4. {
  5. PyObject *val = NULL;
  6. Py_hash_t hash;
  7. Py_ssize_t ix;
  8.  
  9. if (!PyUnicode_CheckExact(key) ||
  10. (hash = ((PyASCIIObject *) key)->hash) == -1) {
  11. hash = PyObject_Hash(key);
  12. if (hash == -1)
  13. return NULL;
  14. }
  15. ix = (self->ma_keys->dk_lookup) (self, key, hash, &val);
  16. if (ix == DKIX_ERROR)
  17. return NULL;
  18. if (ix == DKIX_EMPTY || val == NULL) {
  19. val = default_value;
  20. }
  21. Py_INCREF(val);
  22. return val;
  23. }

2、_PyDict_GetItem_KnownHash

  1. /* Same as PyDict_GetItemWithError() but with hash supplied by caller.
  2. This returns NULL *with* an exception set if an exception occurred.
  3. It returns NULL *without* an exception set if the key wasn't present.
  4. */
  5. PyObject *
  6. _PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
  7. {
  8. Py_ssize_t ix;
  9. PyDictObject *mp = (PyDictObject *)op;
  10. PyObject *value;
  11.  
  12. if (!PyDict_Check(op)) {
  13. PyErr_BadInternalCall();
  14. return NULL;
  15. }
  16.  
  17. ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
  18. if (ix < 0) {
  19. return NULL;
  20. }
  21. return value;
  22. }

3、_PyDict_GetItemId

  1. PyObject *
  2. _PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
  3. {
  4. PyObject *kv;
  5. kv = _PyUnicode_FromId(key); /* borrowed */
  6. if (kv == NULL) {
  7. PyErr_Clear();
  8. return NULL;
  9. }
  10. return PyDict_GetItem(dp, kv);
  11. }
  12.  
  13. /* For backward compatibility with old dictionary interface */

4、PyDict_GetItemString

  1. PyObject *
  2. PyDict_GetItemString(PyObject *v, const char *key)
  3. {
  4. PyObject *kv, *rv;
  5. kv = PyUnicode_FromString(key);
  6. if (kv == NULL) {
  7. PyErr_Clear();
  8. return NULL;
  9. }
  10. rv = PyDict_GetItem(v, kv);
  11. Py_DECREF(kv);
  12. return rv;
  13. }
  14.  
  15. int
  16. _PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
  17. {
  18. PyObject *kv;
  19. kv = _PyUnicode_FromId(key); /* borrowed */
  20. if (kv == NULL)
  21. return -1;
  22. return PyDict_SetItem(v, kv, item);
  23. }
  24.  
  25. int
  26. PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
  27. {
  28. PyObject *kv;
  29. int err;
  30. kv = PyUnicode_FromString(key);
  31. if (kv == NULL)
  32. return -1;
  33. PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
  34. err = PyDict_SetItem(v, kv, item);
  35. Py_DECREF(kv);
  36. return err;
  37. }

六、setdefault(k,v)

setdefault()表示去取字典中的key,如果取不到,则设置新值,相反如果取到,则返回原有默认值

1、dict_setdefault_impl 

  1. /*[clinic input]
  2. dict.setdefault
  3. key: object
  4. default: object = None
  5. /
  6. Insert key with a value of default if key is not in the dictionary.
  7. Return the value for key if key is in the dictionary, else default.
  8. [clinic start generated code]*/
  9.  
  10. static PyObject *
  11. dict_setdefault_impl(PyDictObject *self, PyObject *key,
  12. PyObject *default_value)
  13. /*[clinic end generated code: output=f8c1101ebf69e220 input=0f063756e815fd9d]*/
  14. {
  15. PyObject *val;
  16.  
  17. val = PyDict_SetDefault((PyObject *)self, key, default_value);
  18. Py_XINCREF(val);
  19. return val;
  20. }
  21.  
  22. static PyObject *
  23. dict_clear(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
  24. {
  25. PyDict_Clear((PyObject *)mp);
  26. Py_RETURN_NONE;
  27. }
  28.  
  29. /*[clinic input]
  30. dict.pop
  31. key: object
  32. default: object = NULL
  33. /

2、PyDict_SetDefault

  1. PyObject *
  2. PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
  3. {
  4. PyDictObject *mp = (PyDictObject *)d;
  5. PyObject *value;
  6. Py_hash_t hash;
  7.  
  8. if (!PyDict_Check(d)) {
  9. PyErr_BadInternalCall();
  10. return NULL;
  11. }
  12.  
  13. if (!PyUnicode_CheckExact(key) ||
  14. (hash = ((PyASCIIObject *) key)->hash) == -1) {
  15. hash = PyObject_Hash(key);
  16. if (hash == -1)
  17. return NULL;
  18. }
  19. if (mp->ma_keys == Py_EMPTY_KEYS) {
  20. if (insert_to_emptydict(mp, key, hash, defaultobj) < 0) {
  21. return NULL;
  22. }
  23. return defaultobj;
  24. }
  25.  
  26. if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
  27. if (insertion_resize(mp) < 0)
  28. return NULL;
  29. }
  30.  
  31. Py_ssize_t ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
  32. if (ix == DKIX_ERROR)
  33. return NULL;
  34.  
  35. if (_PyDict_HasSplitTable(mp) &&
  36. ((ix >= 0 && value == NULL && mp->ma_used != ix) ||
  37. (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
  38. if (insertion_resize(mp) < 0) {
  39. return NULL;
  40. }
  41. ix = DKIX_EMPTY;
  42. }
  43.  
  44. if (ix == DKIX_EMPTY) {
  45. PyDictKeyEntry *ep, *ep0;
  46. value = defaultobj;
  47. if (mp->ma_keys->dk_usable <= 0) {
  48. if (insertion_resize(mp) < 0) {
  49. return NULL;
  50. }
  51. }
  52. Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
  53. ep0 = DK_ENTRIES(mp->ma_keys);
  54. ep = &ep0[mp->ma_keys->dk_nentries];
  55. dictkeys_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
  56. Py_INCREF(key);
  57. Py_INCREF(value);
  58. MAINTAIN_TRACKING(mp, key, value);
  59. ep->me_key = key;
  60. ep->me_hash = hash;
  61. if (_PyDict_HasSplitTable(mp)) {
  62. assert(mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
  63. mp->ma_values[mp->ma_keys->dk_nentries] = value;
  64. }
  65. else {
  66. ep->me_value = value;
  67. }
  68. mp->ma_used++;
  69. mp->ma_version_tag = DICT_NEXT_VERSION();
  70. mp->ma_keys->dk_usable--;
  71. mp->ma_keys->dk_nentries++;
  72. assert(mp->ma_keys->dk_usable >= 0);
  73. }
  74. else if (value == NULL) {
  75. value = defaultobj;
  76. assert(_PyDict_HasSplitTable(mp));
  77. assert(ix == mp->ma_used);
  78. Py_INCREF(value);
  79. MAINTAIN_TRACKING(mp, key, value);
  80. mp->ma_values[ix] = value;
  81. mp->ma_used++;
  82. mp->ma_version_tag = DICT_NEXT_VERSION();
  83. }
  84.  
  85. ASSERT_CONSISTENT(mp);
  86. return value;
  87. }

七、update(dict)

update()是把两个字典合并成一个新的字典,中间有交叉的key,更新替换成新值,没有交叉就直接创建

1、dict_update_common

  1. static int
  2. dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
  3. const char *methname)
  4. {
  5. PyObject *arg = NULL;
  6. int result = 0;
  7.  
  8. if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) {
  9. result = -1;
  10. }
  11. else if (arg != NULL) {
  12. if (PyDict_CheckExact(arg)) {
  13. result = PyDict_Merge(self, arg, 1);
  14. }
  15. else {
  16. _Py_IDENTIFIER(keys);
  17. PyObject *func;
  18. if (_PyObject_LookupAttrId(arg, &PyId_keys, &func) < 0) {
  19. result = -1;
  20. }
  21. else if (func != NULL) {
  22. Py_DECREF(func);
  23. result = PyDict_Merge(self, arg, 1);
  24. }
  25. else {
  26. result = PyDict_MergeFromSeq2(self, arg, 1);
  27. }
  28. }
  29. }
  30.  
  31. if (result == 0 && kwds != NULL) {
  32. if (PyArg_ValidateKeywordArguments(kwds))
  33. result = PyDict_Merge(self, kwds, 1);
  34. else
  35. result = -1;
  36. }
  37. return result;
  38. }

2、dict_update

  1. static PyObject *
  2. dict_update(PyObject *self, PyObject *args, PyObject *kwds)
  3. {
  4. if (dict_update_common(self, args, kwds, "update") != -1)
  5. Py_RETURN_NONE;
  6. return NULL;
  7. }
  8.  
  9. /* Update unconditionally replaces existing items.
  10. Merge has a 3rd argument 'override'; if set, it acts like Update,
  11. otherwise it leaves existing items unchanged.
  12. PyDict_{Update,Merge} update/merge from a mapping object.
  13. PyDict_MergeFromSeq2 updates/merges from any iterable object
  14. producing iterable objects of length 2.
  15. */

3、PyDict_Update

  1. int
  2. PyDict_Update(PyObject *a, PyObject *b)
  3. {
  4. return dict_merge(a, b, 1);
  5. }

八、items()将字典转换为列表

1、PyDict_Items

  1. PyObject *
  2. PyDict_Items(PyObject *mp)
  3. {
  4. if (mp == NULL || !PyDict_Check(mp)) {
  5. PyErr_BadInternalCall();
  6. return NULL;
  7. }
  8. return dict_items((PyDictObject *)mp);
  9. }
  10.  
  11. /* Return 1 if dicts equal, 0 if not, -1 if error.
  12. * Gets out as soon as any difference is detected.
  13. * Uses only Py_EQ comparison.
  14. */

九、fromkeys(list,默认值)

1、_PyDict_FromKeys

  1. /* Internal version of dict.from_keys(). It is subclass-friendly. */
  2. PyObject *
  3. _PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
  4. {
  5. PyObject *it; /* iter(iterable) */
  6. PyObject *key;
  7. PyObject *d;
  8. int status;
  9.  
  10. d = _PyObject_CallNoArg(cls);
  11. if (d == NULL)
  12. return NULL;
  13.  
  14. if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
  15. if (PyDict_CheckExact(iterable)) {
  16. PyDictObject *mp = (PyDictObject *)d;
  17. PyObject *oldvalue;
  18. Py_ssize_t pos = 0;
  19. PyObject *key;
  20. Py_hash_t hash;
  21.  
  22. if (dictresize(mp, ESTIMATE_SIZE(PyDict_GET_SIZE(iterable)))) {
  23. Py_DECREF(d);
  24. return NULL;
  25. }
  26.  
  27. while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
  28. if (insertdict(mp, key, hash, value)) {
  29. Py_DECREF(d);
  30. return NULL;
  31. }
  32. }
  33. return d;
  34. }
  35. if (PyAnySet_CheckExact(iterable)) {
  36. PyDictObject *mp = (PyDictObject *)d;
  37. Py_ssize_t pos = 0;
  38. PyObject *key;
  39. Py_hash_t hash;
  40.  
  41. if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
  42. Py_DECREF(d);
  43. return NULL;
  44. }
  45.  
  46. while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
  47. if (insertdict(mp, key, hash, value)) {
  48. Py_DECREF(d);
  49. return NULL;
  50. }
  51. }
  52. return d;
  53. }
  54. }
  55.  
  56. it = PyObject_GetIter(iterable);
  57. if (it == NULL){
  58. Py_DECREF(d);
  59. return NULL;
  60. }
  61.  
  62. if (PyDict_CheckExact(d)) {
  63. while ((key = PyIter_Next(it)) != NULL) {
  64. status = PyDict_SetItem(d, key, value);
  65. Py_DECREF(key);
  66. if (status < 0)
  67. goto Fail;
  68. }
  69. } else {
  70. while ((key = PyIter_Next(it)) != NULL) {
  71. status = PyObject_SetItem(d, key, value);
  72. Py_DECREF(key);
  73. if (status < 0)
  74. goto Fail;
  75. }
  76. }
  77.  
  78. if (PyErr_Occurred())
  79. goto Fail;
  80. Py_DECREF(it);
  81. return d;
  82.  
  83. Fail:
  84. Py_DECREF(it);
  85. Py_DECREF(d);
  86. return NULL;
  87. }

2、dict_fromkeys_impl

  1. static PyObject *
  2. dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
  3. /*[clinic end generated code: output=8fb98e4b10384999 input=382ba4855d0f74c3]*/
  4. {
  5. return _PyDict_FromKeys((PyObject *)type, iterable, value);
  6. }
  7.  
  8. static int
  9. dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
  10. const char *methname)
  11. {
  12. PyObject *arg = NULL;
  13. int result = 0;
  14.  
  15. if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) {
  16. result = -1;
  17. }
  18. else if (arg != NULL) {
  19. if (PyDict_CheckExact(arg)) {
  20. result = PyDict_Merge(self, arg, 1);
  21. }
  22. else {
  23. _Py_IDENTIFIER(keys);
  24. PyObject *func;
  25. if (_PyObject_LookupAttrId(arg, &PyId_keys, &func) < 0) {
  26. result = -1;
  27. }
  28. else if (func != NULL) {
  29. Py_DECREF(func);
  30. result = PyDict_Merge(self, arg, 1);
  31. }
  32. else {
  33. result = PyDict_MergeFromSeq2(self, arg, 1);
  34. }
  35. }
  36. }
  37.  
  38. if (result == 0 && kwds != NULL) {
  39. if (PyArg_ValidateKeywordArguments(kwds))
  40. result = PyDict_Merge(self, kwds, 1);
  41. else
  42. result = -1;
  43. }
  44. return result;
  45. }
  46.  
  47. /* Note: dict.update() uses the METH_VARARGS|METH_KEYWORDS calling convention.
  48. Using METH_FASTCALL|METH_KEYWORDS would make dict.update(**dict2) calls
  49. slower, see the issue #29312. */

十、Clea清空字典

1、PyDict_ClearFreeList

  1. int
  2. PyDict_ClearFreeList(void)
  3. {
  4. PyDictObject *op;
  5. int ret = numfree + numfreekeys;
  6. while (numfree) {
  7. op = free_list[--numfree];
  8. assert(PyDict_CheckExact(op));
  9. PyObject_GC_Del(op);
  10. }
  11. while (numfreekeys) {
  12. PyObject_FREE(keys_free_list[--numfreekeys]);
  13. }
  14. return ret;
  15. }

2、PyDict_Clea

  1. void
  2. PyDict_Clear(PyObject *op)
  3. {
  4. PyDictObject *mp;
  5. PyDictKeysObject *oldkeys;
  6. PyObject **oldvalues;
  7. Py_ssize_t i, n;
  8.  
  9. if (!PyDict_Check(op))
  10. return;
  11. mp = ((PyDictObject *)op);
  12. oldkeys = mp->ma_keys;
  13. oldvalues = mp->ma_values;
  14. if (oldvalues == empty_values)
  15. return;
  16. /* Empty the dict... */
  17. dictkeys_incref(Py_EMPTY_KEYS);
  18. mp->ma_keys = Py_EMPTY_KEYS;
  19. mp->ma_values = empty_values;
  20. mp->ma_used = 0;
  21. mp->ma_version_tag = DICT_NEXT_VERSION();
  22. /* ...then clear the keys and values */
  23. if (oldvalues != NULL) {
  24. n = oldkeys->dk_nentries;
  25. for (i = 0; i < n; i++)
  26. Py_CLEAR(oldvalues[i]);
  27. free_values(oldvalues);
  28. dictkeys_decref(oldkeys);
  29. }
  30. else {
  31. assert(oldkeys->dk_refcnt == 1);
  32. dictkeys_decref(oldkeys);
  33. }
  34. ASSERT_CONSISTENT(mp);
  35. }

3、dict_clear

  1. static PyObject *
  2. dict_clear(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
  3. {
  4. PyDict_Clear((PyObject *)mp);
  5. Py_RETURN_NONE;
  6. }

4、dict_tp_clear

  1. static int
  2. dict_tp_clear(PyObject *op)
  3. {
  4. PyDict_Clear(op);
  5. return 0;
  6. }

Python源码:字典的更多相关文章

  1. [python 源码]字符串对象的实现

    还是带着问题上路吧,和整数对象的实现同样的问题: >>> a='abc' >>> b='abc' >>> a is b True >> ...

  2. [python]源码-对象的创建和行为

    (明天论文就要送审了!!!距离毕业一个月!!!) 现在还记得刚开始学python时候被这种动态语言惊到的那种感觉,列表和字典对象可以随意伸缩,简直不能更帅了,但是一直不知道内部到底是怎么实现的,pyt ...

  3. Python源码读后小结

    Python 笔记 前言(还是叫杂记吧) 在python中一切皆对象, python中的对象体系大致包含了"类型对象", "Mapping对象(dict)", ...

  4. Python源码剖析——02虚拟机

    <Python源码剖析>笔记 第七章:编译结果 1.大概过程 运行一个Python程序会经历以下几个步骤: 由解释器对源文件(.py)进行编译,得到字节码(.pyc文件) 然后由虚拟机按照 ...

  5. Python源码剖析——01内建对象

    <Python源码剖析>笔记 第一章:对象初识 对象是Python中的核心概念,面向对象中的"类"和"对象"在Python中的概念都为对象,具体分为 ...

  6. 读python源码--对象模型

    学python的人都知道,python中一切皆是对象,如class生成的对象是对象,class本身也是对象,int是对象,str是对象,dict是对象....所以,我很好奇,python是怎样实现这些 ...

  7. VS2013编译python源码

    系统:win10 手头有个python模块,是用C写的,想编译安装就需要让python调用C编译器.直接编译发现使用的是vc9编译,不支持C99标准(两个槽点:为啥VS2008都还不支持C99?手头这 ...

  8. 三种排序算法python源码——冒泡排序、插入排序、选择排序

    最近在学习python,用python实现几个简单的排序算法,一方面巩固一下数据结构的知识,另一方面加深一下python的简单语法. 冒泡排序算法的思路是对任意两个相邻的数据进行比较,每次将最小和最大 ...

  9. 《python源码剖析》笔记一——python编译

    1.python的架构: 2.python源码的组织结构: 3.windows环境下编译python:

  10. 转换器5:参考Python源码,实现Php代码转Ast并直接运行

    前两个周末写了<手写PHP转Python编译器>的词法,语法分析部分,上个周末卡文了. 访问器部分写了两次都不满意,没办法,只好停下来,参考一下Python的实现.我实现的部分正好和Pyt ...

随机推荐

  1. 【转】关于web项目中的图片上传、并在前端显示问题(tomcat中配置文件上传虚拟路径)

    一.数据库存储 直接把图片的二进制码存到数据库,可参考blog:http://blog.csdn.net/hope2jiang/article/details/590733 直接存图片在mysql上面 ...

  2. Win32 程序开发:窗口类结构体 WNDCLASS 和 WNDCLASSEX

    一.窗口类结构体简介 窗口类结构体包含了窗口的各种参数信息.比如:窗口的图标.菜单栏.背景颜色.窗口的消息处理等等. 窗口类结构体有两个:WNDCLASS(早期版本) 和 WNDCLASSEX(新版本 ...

  3. 简单的Python GUI界面框架

    Python开发GUI界面, 可以使用pyQT或者wxpython. 不过不论pyQT还是wxpython都需要比较多的学习成本.Python工程往往是用于快速开发的,有些时候引入pyQT,wxpyt ...

  4. Saiku使用iframe嵌入页面访问地址配置化(二十八)--DWR的基本使用

    Saiku使用iframe嵌入页面使用时ip与端口配置化(二十八)--DWR的基本使用 DWR(Direct Web Remoting)是一个用于改善web页面与Java类交互的远程服务器端Ajax开 ...

  5. 【Oracle命令 】使用的sql语句之分组查询(group by)

    由于本人并未对oracle数据库进行深入了解,但是工作中又需要知道一些基础的sql,所以记录下操作的sql语句.方便日后查看 1.将序列号作为分组查询的条件,再将查询出来的结果进行筛选. select ...

  6. 【文本处理命令】之awk命令详解

    一.awk命令简介 awk 是一种很棒的语言,它适合文本处理和报表生成,其语法较为常见,借鉴了某些语言的一些精华,如 C 语言等.在 linux 系统日常处理工作中,发挥很重要的作用,掌握了 awk将 ...

  7. 拎壶学python3-----(3)python之while循环用法

    一.下边我们看一个简单的while循环 那怎么计数呢就让输入三次三次后退出: 二. 关于计数这个问题我们一起看一下 (1)关于计数如下: 我们发现这个计数根本停不下来,怎么才能搞成我们想要的计数次数呢 ...

  8. 图解隐马尔可夫模型(HMM)

    写在前面 最近在写论文过程中,研究了一些关于概率统计的算法,也从网上收集了不少资料,在此整理一下与各位朋友分享. 隐马尔可夫模型,简称HMM(Hidden Markov Model), 是一种基于概率 ...

  9. route 相关设置

    Debian系统 查看路由表: root@debian:~# ip route default via 192.168.6.1 dev enp4s0 10.0.0.0/24 dev br0 proto ...

  10. echarts地图map城市间如何连线

    let bjData = [ [{name:'北京'}, {name:'上海',value:95}], [{name:'北京'}, {name:'广州',value:90}]]; let conver ...