0

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]
Zach
  • 4,624
  • 13
  • 43
  • 60

4 Answers4

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))
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
1
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.

cval
  • 6,609
  • 2
  • 17
  • 14
1

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]}
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

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)
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • @MartijnPieters: I don't think you need to use a generator expression if the data are already zipped together. `dict(data)` should suffice. – Joel Cornett May 26 '12 at 21:06