Converting Dictionary to List?
Your problem is that you have key
and value
in quotes making them strings, i.e. you're setting aKey
to contain the string "key"
and not the value of the variable key
. Also, you're not clearing out the temp
list, so you're adding to it each time, instead of just having two items in it.
To fix your code, try something like:
for key, value in dict.iteritems():
temp = [key,value]
dictlist.append(temp)
You don't need to copy the loop variables key
and value
into another variable before using them so I dropped them out. Similarly, you don't need to use append to build up a list, you can just specify it between square brackets as shown above. And we could have done dictlist.append([key,value])
if we wanted to be as brief as possible.Or just use dict.items()
as has been suggested.
How do you convert a Dictionary to a List?
convert a dictionary to a list is pretty simple, you have 3 flavors for that .keys()
, .values()
and .items()
>>> test = {1:30,2:20,3:10}
>>> test.keys() # you get the same result with list(test)
[1, 2, 3]
>>> test.values()
[30, 20, 10]
>>> test.items()
[(1, 30), (2, 20), (3, 10)]
>>>
(in python 3 you would need to call list on those)finding the maximum or minimum is also easy with the min or max function
>>> min(test.keys()) # is the same as min(test)
1
>>> min(test.values())
10
>>> min(test.items())
(1, 30)
>>> max(test.keys()) # is the same as max(test)
3
>>> max(test.values())
30
>>> max(test.items())
(3, 10)
>>>
(in python 2, to be efficient, use the .iter* versions of those instead )the most interesting one is finding the key of min/max value, and min/max got that cover too
>>> max(test.items(),key=lambda x: x[-1])
(1, 30)
>>> min(test.items(),key=lambda x: x[-1])
(3, 10)
>>>
here you need a key function, which is a function that take one of whatever you give to the main function and return the element(s) (you can also transform it to something else too) for which you wish to compare them.lambda is a way to define anonymous functions, which save you the need of doing this
>>> def last(x):
return x[-1]
>>> min(test.items(),key=last)
(3, 10)
>>>
Converting Dictionary to list then from a list back to dictionary but with the same values
If you mean to create a new dict that would be the same as the first one, but keeping only the keys in your list, that would be
new_dict = {key: serviceli[key] for key in newserli}
So, applied to your sample data, this would give:serviceli = {}
serviceli["Firewall Service"] = "$1.2k/year"
serviceli["Security Ops Centre"] = "$4.2k/year"
serviceli["Hot Site"] = "$8.5k/year"
serviceli["Data Protection"] = "$10.0k/year"
newserli = ["Firewall Service"]
new_dict = {key: serviceli[key] for key in newserli}
print(new_dict)
# {'Firewall Service': '$1.2k/year'}
Converting Python Dictionary to List of lists
lst=[]
lst.append([k,i])
is the same aslst=[k,i]
Not very useful in a loop.To avoid those initialization bugs, "flatten" your dictionary like this (create an artificial list for the key just to be able to add it to the values in a list comprehension):
d={10:[2,"str1",4] , 20:[5,"str2",7] , 30:[8,"str3",10]}
print([[k]+v for k,v in d.items()])
note that the order in the list isn't guaranteed, since order in dicts isn't guaranteed (unless you're using a version where dictionaries keep order like CPython 3.6) How to return dictionary keys as a list in Python?
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. How can I convert a dictionary into a list of tuples?
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
For Python 3.6 and later, the order of the list is what you would expect.In Python 2, you don't need list
.
Converting dict of lists into list of dicts
Here is a pythonic way to do this with list comprehension and lambda functions -
d = {
'x': ['a', 'b'],
'y': [0, 1],
'z': ['foo', 'bar']
}
f = lambda x: {i:j for i,j in zip(d,x)} #Creates the values of final output
g = lambda x: '_'.join([str(j) for i in zip(d,x) for j in i]) #Creates the keys of final output
target = [{g(i):f(i)} for i in zip(*d.values())]
print(target)
[{'x_a_y_0_z_foo': {'x': 'a', 'y': 0, 'z': 'foo'}},
{'x_b_y_1_z_bar': {'x': 'b', 'y': 1, 'z': 'bar'}}]
Convert dictionary to list collection in C#
To convert the Keys to a List of their own:
listNumber = dicNumber.Select(kvp => kvp.Key).ToList();
Or you can shorten it up and not even bother using select:listNumber = dicNumber.Keys.ToList();
Related Topics
Building a Minimal Plugin Architecture in Python
Vectorized Numpy Linspace for Multiple Start and Stop Values
Python Pip on Windows - Command 'Cl.Exe' Failed
How to Have Shared Log Files Under Windows
How to Log a Python Error with Debug Information
Python - Datetime with Timezone to Epoch
Asyncio Cancellederror and Keyboardinterrupt
Hide Chromedriver Console in Python
How to Delete Specific Strings from a File
Mapping a Range of Values to Another
Overflowerror: Long Int Too Large to Convert to Float in Python
Pandas Dataframe Aggregate Function Using Multiple Columns
What Is More 'Pythonic' for 'Not'
Memory Error When Using Pandas Read_Csv
Merging Dictionary Value Lists in Python
How to Explain the Reverse of a Sequence by Slice Notation A[::-1]