This will convert the dict_keys object to a list:
list(newdict.keys())
On the other hand, you should ask yourself whether or not it matters. It is Pythonic to assume duck typing -- if it looks like a duck and it quacks like a duck, it is a duck. The dict_keys object can be iterated over just like a list. For instance:
for key in newdict.keys():
print(key)
Note that dict_keys doesn't support insertion newdict[k] = v, though you may not need it.
This will convert the dict_keys object to a list:
list(newdict.keys())
On the other hand, you should ask yourself whether or not it matters. It is Pythonic to assume duck typing -- if it looks like a duck and it quacks like a duck, it is a duck. The dict_keys object can be iterated over just like a list. For instance:
for key in newdict.keys():
print(key)
Note that dict_keys doesn't support insertion newdict[k] = v, though you may not need it.
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:
>>> newdict = {1:0, 2:0, 3:0}
>>> [*newdict]
[1, 2, 3]
Unpacking with * works with any object that is iterable and, since dictionaries return their keys when iterated through, you can easily create a list by using it within a list literal.
Adding .keys() i.e [*newdict.keys()] might help in making your intent a bit more explicit though it will cost you a function look-up and invocation. (which, in all honesty, isn't something you should really be worried about).
The *iterable syntax is similar to doing list(iterable) and its behaviour was initially documented in the Calls section of the Python Reference manual. With PEP 448 the restriction on where *iterable could appear was loosened allowing it to also be placed in list, set and tuple literals, the reference manual on Expression lists was also updated to state this.
Though equivalent to list(newdict) with the difference that it's faster (at least for small dictionaries) because no function call is actually performed:
%timeit [*newdict]
1000000 loops, best of 3: 249 ns per loop
%timeit list(newdict)
1000000 loops, best of 3: 508 ns per loop
%timeit [k for k in newdict]
1000000 loops, best of 3: 574 ns per loop
with larger dictionaries the speed is pretty much the same (the overhead of iterating through a large collection trumps the small cost of a function call).
In a similar fashion, you can create tuples and sets of dictionary keys:
>>> *newdict,
(1, 2, 3)
>>> {*newdict}
{1, 2, 3}
beware of the trailing comma in the tuple case!
Videos
I am trying to add a list, or a tuple of lists, as the value to a key inside a dictionary. I'm starting with a dictionary that has empty lists as values, and then adding to the value of each key inside a loop like this:
dict = {'key1': [], 'key2': [], 'key3': []}
list = ['a', 'b']
for key,value in dict.items():
# dict[key].append(list)
value.append(list)
print(dict)What is the difference between dict[key].append(list) and value.append(list)? They both produce the same dictionary when the other is commented out.
Further, how would I add a second list to one of these values as a tuple? Something like adding the list ['c', 'd'] to key2, like this:
{'key1': [['a', 'b']], 'key2': [['a', 'b'], ['c', 'd']], 'key3': [['a', 'b']]}Thanks for any replies!
I am trying to key just the key of a dictionary added to a list. But struggling. Ive tried iterating through dict[i] and it outs the value not key so i did a little reading and saw using .keys() but that adds all my keys .
The idea here is that this, if alabama appears makes up 40% of the population, i want it added to a list 40 times. If arizona makes 53% i want it added 53 times so when i do a random choice it will (roughly) pick bama 40 out 100 times and arizona 53 out of 100 times and so on. Currently I am only using 3 states and will eventually use all 50.
ex:
dict = {key:value}
list = [key1,key1,key2,key3,key3,key3,....]
my code
states = {"Alabama":4779736, "Alaska":710231, "Arizona":6392017,}
tot_pop = 0
pop_percent = states #saves dict as new dict so it is not over written
for i in pop_percent: #adds all indiv states pop to get total
tot_pop += pop_percent[i]
for i in pop_percent: #divices indiv state pop by total
ratio = pop_percent[i]/tot_pop
pop_percent[i] = ratio #replaces value with percent
percent = ratio * 100
print(percent)
state_list = []
for i in range(int(percent)):
keys = states.keys()
state_list.append()
print(state_list)results(only put a sample since it was a little difficult to read through)
[dict_keys(['Alabama', 'Alaska', 'Arizona']), dict_keys(['Alabama', 'Alaska', 'Arizona']), dict_keys(['Alabama', 'Alaska', 'Arizona'])]
Let say there is a list inside a dictionary, and in this list there are dictionaries with same keys. So is it possible to get all values for a key inside that list.
I used this ๐
price = dict["data"][:]["price"]
It did'n't worked ofc
Disclamer: I know other ways around(like numpy, def a function, loop etc etc). I just wanna know if it is possible this way.