Convert list into a dictionary
Using the usual grouper recipe, you could do:
Python 2:
d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))
Python 3:
d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))
How to convert a list to a dictionary with indexes as values?
You can get the indices of a list from the built-in enumerate
. You just need to reverse the index-value map and use a dictionary comprehension to create a dictionary:
>>> lst = ['A', 'B', 'C']
>>> {k: v for v, k in enumerate(lst)}
{'A': 0, 'C': 2, 'B': 1}
How do I convert list into dictionary in Python?
What you have is a list of dict(s). So, you could do it as follows.
- If
values
is the name of list variable, thenvalues[i]
gives you access to a dictionary stored at indexi
. - The
dict.get(key, None)
will either return a value or None when the key does not exist. This may allow you to avoid unwanted error when a certain field is absent.
# Use of dict.get(key, "value-when-no-match")
# is safer than directly calling dict[key]
# BUT, this depends on your design/logic/requirements.
values[0].get('what', None)
An Observation
Since "allDay": true
was in your sample data, I assume that most likely you are trying to read this from a JSON file. If that is the case, and if you are using json
library in python, that could be easily dealt with using json.load(), json.loads()
.
Dummy Data
Note that you had a boolean value (for "allDay"
) as true
>> Python expects True
with a capital T.
values = [
{
"what": "Drink",
"allDay": True,
"id": 12,
"when": "2020-05-13",
"end": "2020-05-13"
},
{
"what": "Eat",
"allDay": True,
"id": 14,
"when": "2020-05-14",
"end": "2020-05-14"
}
]
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.
Converting a list to dictionary in python
A dict comprehension will do.
my_list = [2, 3, 5, 7, 11]
my_dict = {k: 0 for k in my_list} # {2:0 , 3:0 , 5:0 , 7:0 , 11:0}
Even if you are not familiar at all with comprehensions you could still do an explicit for
-loop:
my_dict = {}
for k in my_list:
my_dict[k] = 0
Simple way to convert list into dict with False values
As enke suggested you can use fromkeys
method of dict
class to convert the list or any other iterable into a dict by a fixed value for all keys.
In [1]: a = [1,2, "hello"]
In [2]: dict.fromkeys(a, False)
Out[2]: {1: False, 2: False, 'hello': False}
And also you can use dict comprehension as below:
In [1]: a = [1,2, "hello"]
In [2]: {key: False for key in a}
Out[2]: {1: False, 2: False, 'hello': False}
Convert a list of lists to a dictionary
You have zip
as an option:
wanted = {a[0]: list(a[1:]) for a in zip(*x)}
Or if you're familiar with unpacking:
wanted = {k: v for k, *v in zip(*x)}
Convert list of strings to dictionary
Use:
a = ['Tests run: 1', ' Failures: 0', ' Errors: 0']
d = {}
for b in a:
i = b.split(': ')
d[i[0]] = i[1]
print d
returns:
{' Failures': '0', 'Tests run': '1', ' Errors': '0'}
If you want integers, change the assignment in:
d[i[0]] = int(i[1])
This will give:
{' Failures': 0, 'Tests run': 1, ' Errors': 0}
convert list of lists to dictionary
IIUC
>>> temp = [['header1', '4', '8', '16', '32', '64', '128', '256', '512', '243,6'], ['media_range', '1,200', '2,400', '4,800', '4
...: ,800', '6,200', '38,400', '76,800', '153,600', '160,000'], ['speed', '300', '600', '1,200', '2,000', '2,000', '2,000', '2,0
...: 00', '2,000', '2,000']]
>>>
>>> keys = [l[0] for l in temp]
>>> values = [l[1:] for l in temp]
>>> dicts = [dict(zip(keys, sub)) for sub in zip(*values)]
>>>
>>> dicts
[{'header1': '4', 'media_range': '1,200', 'speed': '300'},
{'header1': '8', 'media_range': '2,400', 'speed': '600'},
{'header1': '16', 'media_range': '4,800', 'speed': '1,200'},
{'header1': '32', 'media_range': '4,800', 'speed': '2,000'},
{'header1': '64', 'media_range': '6,200', 'speed': '2,000'},
{'header1': '128', 'media_range': '38,400', 'speed': '2,000'},
{'header1': '256', 'media_range': '76,800', 'speed': '2,000'},
{'header1': '512', 'media_range': '153,600', 'speed': '2,000'},
{'header1': '243,6', 'media_range': '160,000', 'speed': '2,000'}]
Related Topics
How to Print a List with Integers Without the Brackets, Commas and No Quotes
How to Use MySQLdb with Python and Django in Osx 10.6
Finding Moving Average from Data Points in Python
Ioerror: [Errno 22] Invalid Mode ('R') or Filename: 'C:\\Python27\Test.Txt'
Python: Start New Command Prompt on Windows and Wait for It Finish/Exit
Python Multiple Inheritance Passing Arguments to Constructors Using Super
Read a File Line by Line from S3 Using Boto
A Queryset by Aggregate Field Value
Import Module Works in Terminal But Not in Idle
String Similarity Metrics in Python
How to Format Axis Number Format to Thousands with a Comma in Matplotlib
How to Feed Time-Series Data to Stateful Lstm
Convert Year/Month/Day to Day of Year in Python
How to Straighten a Rotated Rectangle Area of an Image Using Opencv in Python