0

I have a dictinary

dict1 = {"one":"1", "two":"2", "three":"3", "four":"4", "five":"5"}

now I want another dictionary say dict2 which contains second and third element of dict1 How can I do this please help Thanks

  • `dict2 = {k: dict1[k] for k in ['two', 'three']}` should work. The list with `['two', 'three']` can be adapted to suit your needs. – GaiusJulius Jul 18 '21 at 11:31
  • 1
    "which contains second and third element" in a dict there's no order, hence there are no "second" and "third" elements. – Nir Alfasi Jul 18 '21 at 11:32
  • @NirAlfasi It depends on the Python version, insertion order is kept since v.3.6. – Guy Jul 18 '21 at 12:07
  • @Guy we shouldn't count on these things... if they want order they should use an [`OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict) ;) – Nir Alfasi Jul 18 '21 at 13:56
  • @NirAlfasi why not? It's part of the language https://stackoverflow.com/q/39980323/5168011 – Guy Jul 18 '21 at 14:33
  • @Guy bc most of the time we don't want to write code that will stop working once we upgrade to python3.7 ;) – Nir Alfasi Jul 18 '21 at 18:15
  • @NirAlfasi But insertion order is also maintained in 3.7, and 3.8, and 3.9, and will be in 3.10 and all future versions of Python 3 because the language documentation says so. So you can write code which relies on this and it won't break when you upgrade (at least possibly until Python 4). – kaya3 Jul 18 '21 at 18:21
  • @kaya3 the real question is why should we count on something like that when there's OrderedDict as I mentioned above (and probably other options as well). – Nir Alfasi Jul 18 '21 at 18:46
  • @NirAlfasi The answer is because `OrderedDict` is an import, whereas standard dictionaries are more convenient, have the benefit of dictionary literal syntax and dictionary comprehensions without having to also call a constructor, and are specified to have ordered behaviour. The real question seems to be why anyone should use `OrderedDict` for versions of Python after 3.6, let alone how anyone can insist it is more correct to do so. – kaya3 Jul 18 '21 at 20:11
  • @kaya3 saying that we shouldn't use the right tool for the right job because it requires an import sounds like a weak argument to me, I guess we will have to agree to disagree. – Nir Alfasi Jul 19 '21 at 07:37
  • @NirAlfasi No, I'm saying regular dicts *are* the right tool for the job when you want insertion order, because they have insertion order and are specified to have insertion order. You have not really offered any counter-argument to that, except to say you don't trust the Python devs not to make backwards-incompatible changes to this specified behaviour (but you do trust them not to make backwards-incompatible changes to `OrderedDict` for some reason). – kaya3 Jul 19 '21 at 10:26
  • As far as I'm concerned, it's like if someone writes `x ** 0.5` and you say no, the right tool for the job is `math.sqrt(x)` because maybe the behaviour of `**` will change in a future version. Well, it won't. – kaya3 Jul 19 '21 at 10:29
  • @kaya3 are you suggesting that at some point the implementation of OrderedDict will become... unordered??? You wanted reasons, here are some: 1. backward compatibility. 2. The insertion order is declared to be maintained in the implementation that CPython provides, what about other implementations? 3. When we're using an OrderedDict we're communication our _intention_ to the other developers more clearly. 4. When we're comparing dictionaries, and the order is meaningful, OrderedDict will be the right choice. Hope this helps. – Nir Alfasi Jul 19 '21 at 11:23
  • @NirAlfasi No, I'm saying that if you trust that `OrderedDict` will stay ordered, then you should trust that `dict` will stay ordered too; because both are specified that way in the language documentation. The insertion order is not *"declared to be maintained in the implementation that CPython provides"*, it is specified in the language documentation, so it is required in every conforming implementation. You seem to persist in misunderstanding this. As for communicating intent, a simple comment like `# this relies on the fact that dictioniaries maintain insertion order` does that too. – kaya3 Jul 19 '21 at 11:26
  • @kaya3 code comments should be used to explain choices we took, not to be counted on so that the code will keep working :) – Nir Alfasi Jul 19 '21 at 11:28
  • @NirAlfasi Your response would have validity if I said you should write a comment so that the code will work correctly, but... of course I did not say that. – kaya3 Jul 19 '21 at 11:29
  • @kaya3 LoL, ok. If all versions of python >=3.6 will support it indefinitely (including all implementations) and we don't need features like `move_to_end()` then I guess we can choose a regular dict. Maybe I'm just being hardheaded... – Nir Alfasi Jul 19 '21 at 11:31

4 Answers4

0
dict2 = {} 
pos = 0 
for x in dict1:   
  if(pos == 1 or pos == 2):     
    dict2[x] = dict1[x]   
  pos += 1
micpog90
  • 106
  • 8
0

in a single line

dict2, positions = {}, (2, 3)
[dict2.update({key: dict1[key]}) for i, key in enumerate(dict1.keys()) if i in positions]

print(dict2)
Ali Aref
  • 1,893
  • 12
  • 31
0

Here's a one-liner using .items() to get an iterable of (key, value) pairs, and the dict constructor to build a new dictionary out of a slice of those pairs:

>>> dict(list(dict1.items())[1:3])
{'two': '2', 'three': '3'}

The slice indices are 1 (inclusive) and 3 (exclusive) since indices count from 0. Note that this uses whatever order the items are in the original dictionary, which will be the order they were inserted in (unless using an old version of Python, in which case the order is generally non-deterministic). If you want a different order, you can use sorted instead of list, perhaps with an appropriate key function.

kaya3
  • 47,440
  • 4
  • 68
  • 97
0

Try this -

dict1 = {"one":"1", "two":"2", "three":"3", "four":"4", "five":"5"}
dict2 = {}
list1 = ['two','three'] # The elements you want to copy

for key in dict1:
    if key in list1:
        dict2[key] = dict1[key]
print(dict2)

Result:

{'two': '2', 'three': '3'}

Or alternatively -

for i in list1:
    dict2[i] = dict1[i]

print(dict2)
PCM
  • 2,881
  • 2
  • 8
  • 30