Reputation: 35
I have a following dictionary:
d1 = {}
I need to assign it the following values, but only the first n
values from the following list:
all_examples= ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']
Final output: d1={"A":[1,1],"B":[2,1]}
I have a following dictionary:
d1 = {'UID': 'A12B4', 'name': 'John', 'email': '[email protected]'}
How do I create a dictionary d2 such that d2 has the first n number of keys and values from d1?
I have a following dictionary: d1 = {}
I need to assign it the following values, but only the first n values from the following list:
all_examples= ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']
Upvotes: 0
Views: 194
Reputation: 24802
How do I create a dictionary d2 such that d2 has the first n number of keys and values from d1?
I'm sorry to tell you, but you shouldn't do that. At least, not with the stock dict
. The reason is that no order is guaranteed in a dict
, and whenever you'll add or remove a value, the order of the dict CAN change.
But if you really insist you could do:
>>> d1 = {1:'a', 3:'b', 2:'c', 4:'d'}
>>> d1
{1: 'a', 2: 'c', 3: 'b', 4: 'd'}
>>> d.keys()[:2]
[1, 2]
>>> {k : d[k] for k in d.keys()[:2]}
{1: 'a', 2: 'c'}
but my suggestion to you is to use an OrderedDict
object, that will guarantee the order of the elements within the dict:
>>> od = OrderedDict()
>>> od[1] = 'a'
>>> od[3] = 'b'
>>> od[2] = 'c'
>>> od[4] = 'd'
>>> od
OrderedDict([(1, 'a'), (3, 'b'), (2, 'c'), (4, 'd')])
>>> od.keys()[:2]
[1, 3]
>>> OrderedDict([(k, od[k]) for k in od.keys()[:2]])
OrderedDict([(1, 'a'), (3, 'b')])
Ok, looks like you just changed radically your question, so here's the new answer:
>>> all_examples= ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']
>>> n = 2
>>> all_examples[:n]
['A,1,1', 'B,2,1']
here's how you select up to n
values of a list.
once again, you're changing your question…
Final output: d1={"A":[1,1],"B":[2,1]}
well you can just do:
>>> {elt[0] : (elt[1], elt[2]) for elt in [elt.split(',') for elt in all_examples[:n]]}
{'A': ('1', '1'), 'B': ('2', '1')}
HTH
Upvotes: 2