What's the best way to initialize (e.g. before a loop) a dictionary that will contain strings and a list in each item?
For instance:
dict = [("string1", [1,2]), ("string2", [5,6]),..]
So:
dict["string1"]
returns:
[1,2]
What's the best way to initialize (e.g. before a loop) a dictionary that will contain strings and a list in each item?
For instance:
dict = [("string1", [1,2]), ("string2", [5,6]),..]
So:
dict["string1"]
returns:
[1,2]
Please don't call a variable dict (or list, or set, etc) because it "covers up" existing functions and prevents you from using them.
data = {
"string1": [1,2],
"string2": [5,6]
}
print data["string1"] # => [1,2]
If you're a bit of a masochist, you can also try
data = dict([("string1",[1,2]), ("string2", [5,6])])
or (per cval's example)
data = dict(zip(strings, numbers))
strings = ["string1","string2"]
numbers = [[1, 2], [5, 6]]
data = {k:v for k,v in zip(strings, numbers)}
And I don't recommend using reserved words (such as dict
) as variable names.
Just pass the list
to the dict()
function, it'll return a dictionary
, and never use dict
as a variable name:
>>> dic = [("string1", [1,2]), ("string2", [5,6])]
>>> dict(dic)
{'string2': [5, 6], 'string1': [1, 2]}
Python 2.7 and Python 3, dict comprehension:
data = {entry[0]: entry[1] for entry in data}
or unpack your structures:
data = {k: v for (k, v) in data}
Python 2.6 and before, generator expression:
data = dict((entry[0], entry[1]) for entry in data)
or again unpack:
data = dict((k, v) for (k, v) in data)
Since your data is already in the form of (key, value) sequences, you can just generate a dict in one go by passing the structure to the dict type without an explicit dict or generator expression:
dict(data)