Αποτελέσματα Αναζήτησης
As mentioned in PythonCookbook, * can be added before a tuple. What does * mean here?. Chapter 1.18. Mapping Names to Sequence Elements:
z = dict(x.items() + y.items()) In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. In Python 3, this will fail because you're adding two dict_items objects together, not two lists -
31 Αυγ 2008 · A Python dict, semantically used for keyword argument passing, is arbitrarily ordered. However, in Python 3.6+, keyword arguments are guaranteed to remember insertion order. "The order of elements in **kwargs now corresponds to the order in which keyword arguments were passed to the function." - What’s New In Python 3.6.
1 Οκτ 2018 · Python 3.9 on: Use lowercase dict in the same method as the accepted answer. typing.Dict and similar upper case generic types which mirror built-ins are deprecated due to PEP 585: def my_func(value: dict[str, int]): pass
Python 3.6 and earlier* If you are talking about a regular dict, then the "first key" doesn't mean anything. The keys are not ordered in any way you can depend on. If you iterate over your dict you will likely not get "banana" as the first thing you see.
Using dict(**orig) will create a new temporary dict that is used as keyword argument for the dict constructor. The constructor will then copy the values from this argument into itself. So you create an additional dictionary with dict(**orig). This is wasteful when the dictionaries are big, as in the original question. –
21 Ιουλ 2010 · Why is it 'better' to use my_dict.keys() over iterating directly over the dictionary? Iteration over a dictionary is clearly documented as yielding keys. It appears you had Python 2 in mind when you answered this, because in Python 3 for key in my_dict.keys() will still have the same problem with changing the dictionary size during iteration.
Python >= 3.5 alternative: unpack into a list literal [*newdict]. New unpacking generalizations (PEP 448) were introduced with Python 3.5 allowing you to now easily do:
24 Φεβ 2011 · @BuvinJ The issue is that json.loads doesn't solve the problem for all use cases where python dict attributes are not JSON serializable. It may help those who are only dealing with simple data structures, from an API for example, but I don't think it's enough of a solution to fully answer the OP's question. –
21 Ιουν 2009 · Another efficient way of doing this with the update method is with keyword arguments, but since they have to be legitimate python words, you can't have spaces or special symbols or start the name with a number, but many consider this a more readable way to create keys for a dict, and here we certainly avoid creating an extra unnecessary dict: