GVKun编程网logo

Python 3上的dict.keys()[0](python3 dict keys)

14

如果您想了解Python3上的dict.keys和[0]的知识,那么本篇文章将是您的不二之选。我们将深入剖析Python3上的dict.keys的各个方面,并为您解答[0]的疑在这篇文章中,我们将为您

如果您想了解Python 3上的dict.keys[0]的知识,那么本篇文章将是您的不二之选。我们将深入剖析Python 3上的dict.keys的各个方面,并为您解答[0]的疑在这篇文章中,我们将为您介绍Python 3上的dict.keys的相关知识,同时也会详细的解释[0]的运用方法,并给出实际的案例分析,希望能帮助到您!

本文目录一览:

Python 3上的dict.keys()[0](python3 dict keys)

Python 3上的dict.keys()[0](python3 dict keys)

我有这句话:

def Ciudad(prob):    numero = random.random()    ciudad = prob.keys()[0]    for i in prob.keys():        if(numero > prob[i]):            if(prob[i] > prob[ciudad]):                ciudad = i        else:            if(prob[i] > prob[ciudad]):                ciudad = i    return ciudad

但是当我调用它时会弹出此错误:

TypeError: ''dict_keys'' object does not support indexing

是版本问题吗?我正在使用Python 3.3.2

答案1

小编典典

dict.keys()是字典视图。list()如果需要键列表,则直接在字典上直接使用,项目0将是(任意)字典顺序中的第一个键:

list(prob)[0]

或者更好的还是使用:

next(iter(dict))

两种方法都可以在Python 2 3中使用,next()对于Python 2
,该选项肯定比使用更为有效dict.keys()。但是请注意,字典 没有 固定的顺序,您将 知道将首先列出哪些键。

似乎您正在尝试查找 最大 密钥,而max()与结合使用dict.get

def Ciudad(prob):    return max(prob, key=prob.get)

对于任何给定的prob字典,函数结果肯定是相同的,因为您的代码在语句的随机数比较分支之间的代码路径中没有差异if

dict.viewkeys()返回的数据类型是什么? [python 2.7]

dict.viewkeys()返回的数据类型是什么? [python 2.7]

@H_301_1@我今天正在学习dict.viewkeys(),我发现我的 python称它为dict_keys对象.我可以将它作为一个可迭代的处理,但它不是一个生成器,因为我可以不止一次迭代它.

根据我的有限知识,我只知道一些数据类型,如String,int,float,list,dict,tuple,set.

但昨天我了解到enumerate()返回一个特殊的数据对,dict()只能使用一次,因此它是一个特殊的元组生成器,带有(index_of_iteration,item)值

这个dict_keys对象是另一个“我不知道它究竟是什么但我知道如何使用它”在python中的对象类型,还是其他什么?

解决方法

它返回一个字典视图对象( https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects).

这是字典中元素的动态视图.即如果您查看字典中的键,如果从字典中删除键,它也将从视图中删除.请参阅以下示例.

来自文档:

>>> dishes = {'eggs': 2,'sausage': 1,'bacon': 1,'spam': 500}
>>> keys = dishes.viewkeys()
>>> values = dishes.viewvalues()

>>> # iteration
>>> n = 0
>>> for val in values:
...     n += val
>>> print(n)
504

>>> # keys and values are iterated over in the same order
>>> list(keys)
['eggs','bacon','sausage','spam']
>>> list(values)
[2,1,500]

>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['spam','bacon']

>>> # set operations
>>> keys & {'eggs','salad'}
{'bacon'}

另见:What are Python dictionary view objects?

python 3.3 dict:如何将struct PyDictKeysObject转换为python类?

python 3.3 dict:如何将struct PyDictKeysObject转换为python类?

我正在尝试修改Brandon Rhodes代码 Routines that examine the internals of a CPython dictionary,以便它适用于cpython 3.3.

我相信我已成功翻译了这个结构.

typedef PyDictKeyEntry *(*dict_lookup_func)
    (PyDictObject *mp,PyObject *key,Py_hash_t hash,PyObject ***value_addr);

struct _dictkeysobject {
    Py_ssize_t dk_refcnt;
    Py_ssize_t dk_size;
    dict_lookup_func dk_lookup;
    Py_ssize_t dk_usable;
    PyDictKeyEntry dk_entries[1];
};

我认为以下看起来很好:

from ctypes import Structure,c_ulong,POINTER,cast,py_object,CFUNCTYPE

LOOKUPFUNC = CFUNCTYPE(POINTER(PyDictKeyEntry),POINTER(PyDictObject),POINTER(POINTER(py_object)))

class PyDictKeysObject(Structure):
"""A key object"""
_fields_ = [
    ('dk_refcnt',c_ssize_t),('dk_size',('dk_lookup',LOOKUPFUNC),('dk_usable',('dk_entries',PyDictKeyEntry * 1),]

PyDictKeysObject._dk_entries = PyDictKeysObject.dk_entries
PyDictKeysObject.dk_entries = property(lambda s: 
    cast(s._dk_entries,POINTER(PyDictKeyEntry * s.dk_size))[0])

这行代码现在有效,其中d == {0:0,1:1,2:2,3:3}:

obj = cast(id(d),POINTER(PyDictObject)).contents  # works!!`

这是我在C struct PyDictObject中的翻译:

class PyDictObject(Structure):  # an incomplete type
    """A dictionary object."""

def __len__(self):
    """Return the number of dictionary entry slots."""
    pass

def slot_of(self,key):
    """Find and return the slot at which `key` is stored."""
    pass

def slot_map(self):
    """Return a mapping of keys to their integer slot numbers."""
    pass

PyDictObject._fields_ = [
    ('ob_refcnt',('ob_type',c_void_p),('ma_used',('ma_keys',POINTER(PyDictKeysObject)),('ma_values',POINTER(py_object)),# points to array of ptrs
]

解决方法

我的问题是访问cpython 3.3中实现的python字典的C结构.我开始使用cpython / Objects / dictobject.c和Include / dictobject.h中提供的C结构.定义字典涉及三个C结构:PyDictObject,PyDictKeysObject和PyDictKeyEntry.每个C结构到python的正确转换如下.评论表明我需要修复的地方.感谢@eryksun指导我一路走来!
class PyDictKeyEntry(Structure):
"""An entry in a dictionary."""
    _fields_ = [
        ('me_hash',c_ulong),('me_key',py_object),('me_value',]

class PyDictObject(Structure):
    """A dictionary object."""
    pass

LOOKUPFUNC = CFUNCTYPE(POINTER(PyDictKeyEntry),POINTER(POINTER(py_object)))

class PyDictKeysObject(Structure):
"""An object of key entries."""
    _fields_ = [
        ('dk_refcnt',# a function prototype per docs 
        ('dk_usable',# an array of size 1; size grows as keys are inserted into dictionary; this variable-sized field was the trickiest part to translate into python
    ]   

PyDictObject._fields_ = [
    ('ob_refcnt',# Py_ssize_t translates to c_ssize_t per ctypes docs
    ('ob_type',# Could not find this in the docs
    ('ma_used',# Py_Object* translates to py_object per ctypes docs
]

PyDictKeysObject._dk_entries = PyDictKeysObject.dk_entries
PyDictKeysObject.dk_entries = property(lambda s: cast(s._dk_entries,POINTER(PyDictKeyEntry * s.dk_size))[0])  # this line is called every time the attribute dk_entries is accessed by a PyDictKeyEntry instance; it returns an array of size dk_size starting at address _dk_entries. (POINTER creates a pointer to the entire array; the pointer is dereferenced (using [0]) to return the entire array); the code then accesses the ith element of the array)

以下函数提供对python字典底层的PyDictObject的访问:

def dictobject(d):
    """Return the PyDictObject lying behind the Python dict `d`."""
    if not isinstance(d,dict):
        raise TypeError('cannot create a dictobject from %r' % (d,))
    return cast(id(d),POINTER(PyDictObject)).contents

如果d是具有键值对的python字典,则obj是包含键值对的PyDictObject实例:

obj = cast(id(d),POINTER(PyDictObject)).contents

PyDictKeysObject的一个实例是:

key_obj = obj.ma_keys.contents

指向存储在字典的插槽0中的密钥的指针是:

key_obj.dk_entries[0].me_key

使用这些类的程序以及探测插入到字典中的每个键的哈希冲突的例程位于here.我的代码是由Brandon Rhodes为python 2.x编写的代码的修改.他的代码是here.

Python 3.6的dict竟然是有序的!dict和OrderedDict的用法示例

Python 3.6的dict竟然是有序的!dict和OrderedDict的用法示例

目录

一、关于dict()函数

二、代码(结果)


一、关于dict()函数

1.详情看网址:https://mail.python.org/pipermail/python-dev/2016-September/146327.html

2.3.6版本的Python已经使得dict变得紧凑以及关键字变得有序

二、代码(结果)

dict()OrderedDict()用法在代码中有详细的注释OrderedDict需要从collections包中导入,值得注意的是3.6版本的dict()函数使得结果不再无序

"""
@author:nickhuang1996
"""
from collections import OrderedDict

if __name__ == ''__main__'':
    ''''''dict()''''''
    champions1 = dict()
    champions1[''乔峰''] = 1
    champions1[''段誉''] = 3
    champions1[''虚竹''] = 2
    print("champions1:{}".format(champions1))#champions1:{''乔峰'': 1, ''段誉'': 3, ''虚竹'': 2}
    print("")
    print("显示value:")
    for value in champions1:
        print("{}".format(value))
    print("")
    print("显示key和value:")
    for key, value in champions1.items():
        print("{},{}".format(key, value))
    print("")
    #keys()显示键值
    print("keys()显示键值:")
    print(list(champions1.keys()))#[''乔峰'', ''段誉'', ''虚竹'']
    print("")
    #values()显示每个value
    print("values()显示每个value:")
    print(list(champions1.values()))#[1, 3, 2]
    print("")
    #values()[k]显示第k个value
    print("values()[k]显示第k个value:")
    print(list(champions1.values())[0])#1
    print(list(champions1.values())[1])#3
    print(list(champions1.values())[2])#2
    print("")
    #values()index(k)通过value值找对应的序号
    print("values()index(k)通过value值找key的序号:")
    print(list(champions1.values()).index(1))#0
    print(list(champions1.values()).index(2))#2
    print(list(champions1.values()).index(3))#1
    print("")
    #keys()values()index(k)通过value值找key的序号找到对应的key
    print("keys()values()index(k)通过value值找key的序号找到对应的key:")
    print((list(champions1.keys())[list(champions1.values()).index(1)]))#乔峰
    print((list(champions1.keys())[list(champions1.values()).index(2)]))#虚竹
    print((list(champions1.keys())[list(champions1.values()).index(3)]))#段誉
    print("")
    #sorted(values())按照value值排序
    print("sorted(values())按照value值排序:")
    champions1 = dict([(list(champions1.keys())[list(champions1.values()).index(value)],value) for value in sorted(champions1.values())])
    print(champions1)#{''乔峰'': 1, ''虚竹'': 2, ''段誉'': 3}
    print("")
    ''''''OrderedDict''''''
    champions2 = OrderedDict()
    champions2[''乔峰''] = 1
    champions2[''段誉''] = 3
    champions2[''虚竹''] = 2
    print("champions2:{}".format(champions2))#champions2:OrderedDict([(''乔峰'', 1), (''段誉'', 3), (''虚竹'', 2)])
    print("")
    print("显示value:")
    for value in champions2:
        print("{}".format(value))
    print("")
    print("显示key和value:")
    for key, value in champions2.items():
        print("{},{}".format(key, value))
    print("")
    #sorted(values())按照value值排序
    print("sorted(values())按照value值排序:")
    champions2 = OrderedDict([(list(champions2.keys())[list(champions2.values()).index(value)],value) for value in sorted(champions2.values())])
    print(champions2)#OrderedDict([(''乔峰'', 1), (''虚竹'', 2), (''段誉'', 3)])
    print("")

本文同步分享在 博客“悲恋花丶无心之人”(CSDN)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

Python 3中的Python 2 dict_items.sort()

Python 3中的Python 2 dict_items.sort()

我正在将一些代码从Python 2移植到3。这是Python 2语法中的有效代码:

def print_sorted_dictionary(dictionary):      items=dictionary.items()      items.sort()

在Python 3中,dict_items没有方法’sort’-如何在Python 3中解决此问题?

答案1

小编典典

使用items = sorted(dictionary.items()),它在Python 2 Python 3中都很好用。

关于Python 3上的dict.keys[0]的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于dict.viewkeys()返回的数据类型是什么? [python 2.7]、python 3.3 dict:如何将struct PyDictKeysObject转换为python类?、Python 3.6的dict竟然是有序的!dict和OrderedDict的用法示例、Python 3中的Python 2 dict_items.sort()等相关内容,可以在本站寻找。

本文标签: